ISC Recursion Programs

Write a recursion method to count the number of digits

int count(int n)
{

    if(n==0)

        return 1;

    return 1+count(n/10);

}

Write a recursive method to convert decimal number to binary number

void dectobin(int n,int r){

    if(n==0)

    {

        System.out.println("Binary is:"+r);

    }

    int d=n%2;

    r=r*10+d;

    dectobin(n/2,r);

}

Write a recursive method check a number is prime number or not

int count(int n){

    if(n==0)

        return 0;

    int d=n%2;

    return ((d==1)?1:0)+count(n/2);

}

void check(int n){

    if(count(n)==2)

        System.out.println("Prime number");

    else 

        System.out.println("Non-Prime number");

}

Write a recursive method to find the minimum value present in an array

int fmin(int arr[],int n )

{

    if(n==0)

        return 999999;

    return Math.min(arr[n-1],fmin(arr,n-1));

}

Write a recursive method to find the sum of the numbers present in an array

int fsum(int arr[],int n )
{

    if(n==0)

        return 0;

    return arr[n-1]+fsum(arr,n-1);

}

Write a recursive method to reverse a word or sentence

void reverse(String n,String r)
{
    if(n.length()==0)
    {
        System.out.println("Reverse of the number is:"+r);
        return;
    }
    return reverse(n.substring(n.length()-1),r+n.charAt(n.length()-1));
} 

Write a recursive method to find the prime factors of a number

void primefact(int n,int i)
{
    if(n>=i)
    {
        System.out.println(i);
        return;
    }
    if(n%i==0)
    {
        System.out.println(i);
        primefact(n/i,i);
    }
    primefact(n,i+1);
}

Write a recursive method to display hailstone sequence of numbers until n terms

void hailstone(int n){
    if(n==1){
        System.out.println(n);
        return;
    }
    if(n%2==0){
        System.out.println(n/2);
        hailstone(n/2);
    }
    else{
        System.out.println(3*n+1);
        hailstone(3*n+1);
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top