Recursive methods
In this chapter you will learn:
- What is a recursive methods
- How to write recursive methods
- Display a string in reverse by using recursion
- How to calculate fibonacci value in C#
Description
A method can call itself is called recursion.
Example
How to write recursive methods
using System; //from w w w . java2 s . c om
class Factorial {
// This is a recursive function.
public int factR(int n) {
int result;
if(n==1) return 1;
result = factR(n-1) * n;
return result;
}
// This is an iterative equivalent.
public int factI(int n) {
int t, result;
result = 1;
for(t=1; t <= n; t++)
result *= t;
return result;
}
}
class MainClass {
public static void Main() {
Factorial f = new Factorial();
Console.WriteLine("Factorials using recursive method.");
Console.WriteLine("Factorial of 3 is " + f.factR(3));
Console.WriteLine("Factorial of 4 is " + f.factR(4));
Console.WriteLine("Factorial of 5 is " + f.factR(5));
Console.WriteLine();
Console.WriteLine("Factorials using iterative method.");
Console.WriteLine("Factorial of 3 is " + f.factI(3));
Console.WriteLine("Factorial of 4 is " + f.factI(4));
Console.WriteLine("Factorial of 5 is " + f.factI(5));
}
}
The code above generates the following result.
Example 2
using System; // ww w. j a v a2 s .c om
class RevStr {
public void displayRev(string str) {
if(str.Length > 0)
displayRev(str.Substring(1, str.Length-1));
else
return;
Console.Write(str[0]);
}
}
class MainClass {
public static void Main() {
string s = "this is a test";
RevStr rsOb = new RevStr();
Console.WriteLine("Original string: " + s);
Console.Write("Reversed string: ");
rsOb.displayRev(s);
Console.WriteLine();
}
}
The code above generates the following result.
Example 3
using System;/* w w w. j a va 2 s . c om*/
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
public class MainClass
{
public static void Main(){
Console.WriteLine(Fibonacci(10));
}
static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Return value from a function
- Syntax to return a value from a method
- How to return value from a function
- How to return an object value from a method
- How to return a value of an array from a method