Recursion Fundamentals

1. Java Program to Reverse a Sentence Using Recursion

learn to reverse a given sentence using a recursive loop in Java.

Example: Reverse a Sentence Using Recursion
package com.programiz;

public class ReverseSentence {
    
    public static void main(String[] args) {
        
        String sentence = "Go work";
        String reversed = reverse(sentence);
        System.out.println("The reversed sentence is: " + reversed);
    }
    
    public static String reverse(String sentence) {
        
        if (sentence.isEmpty())
            return sentence;
        
        return reverse(sentence.substring(1)) + sentence.charAt(0);
    }
}

When you run the program, the output will be:

The reversed sentence is: krow oG

In the above program, we’ve a recursive function reverse().

On each iteration, we add (concatenate) the result of next reverse() function to the first character of sentence using charAt(0).

The recursive call must be before the charAt(), because that way the last characters will start adding to the left hand side. If you reverse the order, you’ll end up with the original sentence.

In the end, we end up with an empty sentence and reverse() returns the reversed sentence.

Iterationreverse()substring()reversedString
1reverse(“Go work”)“o work”result + “G”
2reverse(“o work”)" work"result + “o” + “G”
3reverse(" work")“work”result + " " + “o” + “G”
4reverse(“work”)“ork”result + “w” + " " + “o” + “G”
5reverse(“ork”)“rk”result + “o” + “w” + " " + “o” + “G”
6reverse(“rk”)“k”result + “r” + “o” + “w” + " " + “o” + “G”
7reverse(“k”)“”result + “k” + “r” + “o” + “w” + " " + “o” + “G”
Finalreverse("")-“” + “k” + “r” + “o” + “w” + " " + “o” + “G” = “krow oG”

2. Java Program to Convert Binary Number to Decimal and vice-versa

Visit this page to learn how to convert binary number to decimal.

Example 1: Program to convert binary number to decimal

package com.programiz;

public class BinaryToDecimal {
    
    public static void main(String[] args) {
        
        long num = 110110111;
        int decimal = convertBinaryToDecimal(num);
        System.out.printf("%d in binary = %d in decimal", num, decimal);
    }
    
    public static int convertBinaryToDecimal(long num) {
        
        int decimalNumber = 0;
        int i = 0;
        long remainder;
        
        while (num != 0) {
            remainder = num % 10;
            num /= 10;
            decimalNumber += remainder * Math.pow(2, i);
            ++i;
        }
        return decimalNumber;
    }
}

When you run the program, the output will be:

110110111 in binary = 439 in decimal

Visit this page to learn, how to convert decimal number to binary.

Example 2: Program to convert decimal number to binary

package com.programiz;

public class DecimalToBinary {
    
    public static void main(String[] args) {
        
        int num = 19;
        long binary = convertDecimalToBinary(num);
        System.out.printf("%d in decimal = %d in binary", num, binary);
    }
    
    public static long convertDecimalToBinary(int n) {
        
        long binaryNumber = 0;
        int remainder, i = 1, step = 1;
        
        while (n != 0) {
            remainder = n % 2;
            System.out.printf("Step %d: %d / 2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n / 2);
            n /= 2;
            binaryNumber += remainder * i;
            i *= 10;
        }
        return binaryNumber;
    }
}

When you run the program, the output will be:

Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary

3. Java Program to Find GCD of two Numbers

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).

This is done by using for and while loops with the help of if else statements.

Example 1: Find GCD of two numbers using for loop and if statement

package com.programiz;

public class GCD {
    
    public static void main(String[] args) {
        
        int n1 = 81, n2 = 153, gcd = 1;
        
        for (int i = 1; i <= n1 && i <= n2; ++i) {
            // Checks if i is factor of both integers
            if (n1 % i == 0 && n2 % i == 0) {
                gcd = i;
            }
        }
        
        System.out.println("G.C.D of %d and %d is %d", n1, n2, gcd);
    }
}

When you run the program, the output will be:

G.C.D of 81 and 153 is 9

Here, two numbers whose GCD are to be found are stored in n1 and n2 respectively.

Then, a for loop is executed until i is less than both n1 and n2. This way, all numbers between 1 and smallest of the two numbers are iterated to find the GCD.

If both n1 and n2 are divisble by i, gcd is set to the number. This goes on until it finds the largest number (GCD) which divides both n1 and n2 without remainder.

Example 2: Find GCD of two numbers using while loop and if else statement

package com.programiz;

public class GCD {
    
    public static void main(String[] args) {
        
        int n1 = 81, n2 = 153;
        
        while (n1 != n2) {
            
            if (n1 > n2) {
                n1 -= n2;
            } else {
                n2 -= n1;
            }
        }
        
        System.out.println("G.C.D = " + n1);
    }
}

When you run the program, the output will be:

G.C.D = 9

This is a better way to find the GCD. In this method, smaller integer is subtracted from the larger integer, and the result is assigned to the variable holding larger integer. This process is continued until n1 and n2 are equal.

The above two programs works as intended only if the user enters positive integers. Here’s a little modification of the second example to find the GCD for both positive and negative integers.

Example 3: GCD for both positive and negative numbers

package com.programiz;

public class GCD {
    
    public static void main(String[] args) {
        
        int n1 = 81, n2 = -153;
        
        // Always set to positive
        n1 = (n1 > 0) ? n1 : -n1;
        n2 = (n2 > 0) ? n2 : -n2;
        
        while (n1 != n2) {
            
            if (n1 > n2) 
            	n1 -= n2;
            else
                n2 -= n1;
        }
        
        System.out.println("G.C.D = " + n1);
    }
}

When you run the program, the output will be:

G.C.D = 9

4. Java Program to Find G.C.D Using Recursion

In this program, you’ll learn to find the GCD (Greatest Common Divisor) or HCF using a recursive function in Java.

This program takes two positive integers and calculates GCD using recursion.

package com.programiz;

public class FindGCD {
    
    public static void main(String[] args) {
        
        int n1 = 366, n2 = 60;
        int hcf = findHCF(n1, n2);
        
        System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf);
    }
    
    public static int findHCF(int n1, int n2) {

        if (n2 != 0) 
            return findHCF(n2, n1 % n2);
        else
            return n1;        
    }
}

When you run the program, the output will be:

G.C.D of 366 and 60 is 6.

In the above program, the recursive function is called until n2 is 0. In the end, the value of n1 is the GCD or HCF of the given two numbers.

No.Recursive calln1n2n1 % n2
1findHCF(366, 60)366606
2findHCF(60, 6)6060
FinalfindHCF(6, 0)60-

5. Java Program to Find Factorial of a Number Using Recursion

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

The factorial of a negative number doesn’t exist. And the factorial of 0 is 1.

Learn to find the factorial of a number using recursion in this example. how you can find the factorial of a number using loop?

Java Program to Find Factorial of a Number

In this program, you’ll learn to find the factorial of a number using for and while loop in Java.

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

Example 1: Find Factorial of a number using for loop

package com.programiz;

public class Factorial {
    
    public static void main(String[] args) {
        
        int num = 10;
        long factorial = 1;
        
        for (int i = 1; i <= num; i++) {
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

When you run the program, the output will be:

Factorial of 10 = 3628800

In this program, we’ve used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.

We’ve used long instead of int to store large results of factorial. However, it’s still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable declared in java.math library.

Example 2: Find Factorial of a number using BigInteger

package com.programiz;

import java.math.BigInteger;

public class Factorial {
    
    public static void main(String[] args) {
        
        int num = 30;
        BigInteger factorial = BigInteger.ONE;
        for (int i = 1; i <= num; ++i) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

When you run the program, the output will be:

Factorial of 30 = 265252859812191058636308480000000

Here, instead of long, we use BigInteger variable factorial.

Since, * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be casted to BigInteger for multiplication.


Likewise, we can also use a while loop to solve this problem.

Example 3: Find Factorial of a number using while loop

package com.programiz;

public class Factorial {
    
    public static void main(String[] args) {
        
        int num = 5, i = 1;
        long factorial = 1;
        
        while (i <= num) {
            factorial *= i;
            i++;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

When you run the program, the output will be:

Factorial of 5 = 120

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It’s because the number of iteration (upto num) is known.

Example 4: Factorial of a Number Using Recursion

package com.programiz;

public class Factorial {
    
    public static void main(String[] args) {
        
        int num = 6;
        long factorial = multiplyNumbers(num);
        System.out.println("Factorial of " + num + " = " + factorial);
    }
    
    public static long multiplyNumbers(int num) {
        if (num >= 1) 
            return num * multiplyNumbers(num - 1);
        else 
            return 1;
    }
}

When you run the program, the output will be:

Factorial of 6 = 720

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed. Since, it is called from the same function, it is a recursive call.

In each recursive call, the value of argument num is decreased by 1 until num reaches less than 1.

When the value of num is less than 1, there is no recursive call.

And each recursive calls returns giving us:

6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720

6. Java Program to calculate the power using recursion

Example: Program to calculate power using recursion

package com.programiz;

public class Power {
    
    public static void main(String[] args) {

        int  base = 3, powerRaised = 4;
        int result = power(base, powerRaised);
        
        System.out.printf("%d^%d = %d", base, powerRaised, result);
    }
    
    public static int power(int base, int powerRaised) {
        
        if (powerRaised != 0) 
            return (base * power(base, powerRaised - 1));
        else 
            return 1;        
    }
}

When you run the program, the output will be:

3^4 = 81

In the above program, you calculate the power using a recursive function power().

In simple terms, the recursive function multiplies the base with itself for powerRaised times, which is:

3 * 3 * 3 * 3 = 81
Iterationpower()powerRaisedresult
1power(3, 4)43 * result2
2power(3, 3)33 * 3 * result3
3power(3, 2)23 * 3 * 3 * result4
4power(3, 1)13 * 3 * 3 * 3 * resultfinal
Finalpower(3, 0)03 * 3 * 3 * 3 * 1 = 81

Java Program to Calculate the Power of a Number

Example 1: Calculate power of a number using a while loop

package com.programiz;

public class Power {
    
    public static void main(String[] args) {
        
        int base = 3, exponent = 4;
        long result = 1;
        
        while (exponent != 0) {
            result *= base;
            --exponent;
        }
        
        System.out.println("Answer = " + result);
    }
}

When you run the program, the output will be:

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying result by base until exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.


Example 2: Calculate power of a number using a for loop

package com.programiz;

public class Power {
    
    public static void main(String[] args) {
        
        int base = 3, exponent = 4;
        long result = 1;
        
        for (; exponent != 0; --exponent) {
            result *= base;
        }
        
        System.out.println("Answer = " + result);
    }
}

Here, instead of using a while loop, we’ve used a for loop.

After each iteration, exponent is decremented by 1, and result is multiplied by base exponent number of times.

Both programs above doesn’t work if you have a negative exponent. For that, you need to use pow() function in Java standard library.

Example 3: Calculate the power of a number using pow() function

package com.programiz;

public class Power {
    
    public static void main(String[] args) {
        
        int base = 3, exponent = -4;
        double result = Math.pow(base, exponent);
        
        System.out.println("Answer = " + result);
    }
}

When you run the program, the output will be:

Answer = 0.012345679012345678

In this program, we use Java’s Math.pow() function to calculate the power of the given base.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值