Recursive Function Examples

Recursive function is a function that calls itself, either directly or indirectly. Below are some of the examples of recursive functions, written in Java, that are beneficial for the ISC students.

Finding the Factorial

public long fact(long n){
    if(n <= 1)
        return 1L;
    else
        return n * fact(n - 1);
}

Sum of the Digits

public int sum(int n){
    if(n < 10)
        return n;
    else
        return n % 10 + sum(n / 10);
}

Count the number of digits

public int count(int n){
    if(n < 10)
        return 1;
    else
        return 1 + count(n / 10);
}

Finding GCD

public int gcd(int p, int q){
    if(q == 0)
        return p;
    else
        return gcd(q, p % q);
}

Finding ab

public int power(int a, int b){
    if(b == 0)
        return 1;
    else if(b == 1)
        return a;
    else
        return a * power(a, b - 1);
}

Generating Factorial Terms

public long fact(int n){
    if(n == 1)
        return 0;
    else if(n == 2)
        return 1;
    else
        return fact(n - 1) + fact(n - 2);
}

Displaying Factors of a Number

public static void factors(int num, int f){
    if(num == f)
        System.out.println(f);
    else if(num % f == 0){
        System.out.println(f);
        factors(num, f + 1);
    }
    else
        factors(num, f + 1);
}

Leave a Reply

%d bloggers like this: