Advertisement
//C# Example of a simple(non-recursive) method
using System;
class A
{
//Defining the Steps() method of class A
void Steps(int a)
{
for(int x=a;x<=5;x++)
{
for(int y=1;y<=x;y++)
{
Console.Write(y);
}
Console.WriteLine();
}
}
//Defining the Main() method of class A
public static void Main(String[] ar)
{
//A local variable
int i=1;
//Creating an object of class A
A ob = new A();
//Calling the steps() method of class A
ob.Steps(i);
}
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
//C# Example of a recursive method
using System;
class A
{
//Defining a method of class A
void Steps(int a)
{
if(a<=5)
{
for(int x=1;x<=a;x++)
{
Console.Write(x);;
}
Console.WriteLine();
//Recursive method calling itself from its own code
Steps(a+1);
}
}
//Defining a method of class A
public static void Main(String[] ar)
{
//A local variable
int i=1;
//Creating an object of class A
A ob = new A();
//Calling the steps() method of class A
ob.Steps(i);
}
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Advertisement
//C# Recursion Example - Finding Factorial
using System;
class A
{
public static void Main(String[] ar)
{
//Creating an object of class A
A ob = new A();
//Local variable whose factorial is to be found
int num = 5;
//Calling the recursive method to calculate a factorial of an int local variable
int result = ob.Factor(num);
//Printig the result of factorial
Console.WriteLine("Factorial of 5 is " + result);
}
//Defining a recursive method of class A
int Factor(int a)
{
//Local variable
int result;
if(a==1)
return 1;
else
result = a * Factor(a-1); // recursive method factor has called itself
//Returning the final result
return result;
}
}
Factorial of 5 is 120
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement