How to write recursive methods

Description

A method can call itself is called recursion.

Example

How to write recursive methods


using System; // www  .j  a v  a2 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; /*  w w w  . ja  va 2 s  . c o m*/
  
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;/*ww w . j a  va2  s .  c o  m*/
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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor