Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts

Friday, 17 June 2016

Program to print 1 to 10 using Recursion.

Explanation :
Recursion means calling a method within itself until it returns a value.

Code:

public class Print
{
       public static void recursive(int n)
      {
        if(n <= 10)
       {
              System.out.println(n);
              recursive(n+1);
       }
       }

       public static void main(String args[])
      {
       recursive(1);
       }
 }

Thursday, 16 June 2016

Program to print Fibonacci series using Recursion.

Explanation :
In Fibonacci series, next number is the sum of previous two numbers.
For example: If count =10 then output will be 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Recursion means calling a method within itself until it returns a value.

Code:

public class Fibonacci

    static int n1=0,n2=1,n3=0;   
    static void printFibonacci(int count)
   {   
        if(count>0)
       {   
         n3 = n1 + n2;   
         n1 = n2;   
         n2 = n3;   
         System.out.print(" "+n3);  
         printFibonacci(count-1);   
       }   
    }   
    public static void main(String args[])
   {   
      int count=10;   
      System.out.print(n1+" "+n2);//printing 0 and 1   
      printFibonacci(count-2);//n-2 because 2 numbers are already printed  
    } 
}

Program to find Factorial of a number using Recursion.

Explanation :
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120.
Recursion means calling a method within itself until it returns a value.

Code:

class Factorial
{  
    static int factorial(int n)
   {    
      if (n == 0)    
         return 1;    
      else    
         return(n * factorial(n-1));    
     }    
     public static void main(String args[])
     {  
      int i,fact=1;  
      int number=4;   
      fact = factorial(number);   
      System.out.println("Factorial of "+number+" is: "+fact);    
     }  
}

 

Program to know whether a number is Armstrong or not using Recursion.

Explanation :
Recursion means calling a method within itself until it returns a value.
(If n=153 then Armstrong = 1*1*1 + 5*5*5 + 3*3*3 i.e,
Armstrong =1+125+27=153.)

Code:

import java.util.*;
class armstrong
{
     public static void main(String args[])
    {
      int i,n,sum,m;
      Scanner sc=new Scanner(System.in);
      System.out.print("Enter a number : ");
      n=sc.nextInt(); 
      armstrong obj= new armstrong();
      m=obj.checknum(n); 
      if(n==m)
         System.out.println("It is a armstrong number");
      else
         System.out.println("Not a armstrong number");
     }
     int checknum(int n)
     {
        if(n==0)
             return 0;
         else
             return (int)Math.pow(n%10,3)+ checknum(n/10);
     }
}