Recursive methods

Recursive methods: Method which call itself is called recursive method. It consist of termination condition and recursive condition.

Example 1: Write a program to print 1 to 20 without using loops?
package com.java.basics;

public class Recursion {
    
    public static void display(int n){
        if(n == 21){
            return;
        }
        System.out.print(n + " ");
        display(n + 1);
    }
    
    public static void main(String[] args) {
        display(1);
    }
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Example 2: Write a program to find GCD of two numbers?
package com.java.basics;

public class Recursion {
    
    public static int gcd(int a, int b){
        if(b == 0){
            return a;
        }
        return gcd(b, a % b);
    }
 
    public static void main(String[] args) {
        System.out.println("GCD of 54 and 24 is  " + gcd(54,24));
        System.out.println("GCD of 48 and 180 is  " + gcd(48, 180));
    }
}

Output:
GCD of 54 and 24 is 6
GCD of 48 and 180 is 12

No comments:

Post a Comment