Program to Calculate power using Recursion 

Calculate power using recursion

Java Program to calculate the power using recursion, this is a basic program for starting recursion, below program, is taken from coding ninjas platform.

Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer.

Do this recursively.

Input format :
Two integers x and n (separated by space)
Output Format :
x^n (i.e. x raise to the power n)
Constraints :
0 <= x <= 30
0 <= n <= 30
Sample Input 1 :
 3 4
Sample Output 1 :
81
Sample Input 2 :
 2 5
Sample Output 2 :
32

Power using recursion solution in Java :

import java.util.Scanner;

public class Runner {

	static Scanner s = new Scanner(System.in);

	public static void main(String[] args) {
		int x = s.nextInt();
		int n = s.nextInt();
		
		System.out.println(Solution.power(x, n));
	}
}
public class Solution {

	public static int power(int x, int n) {
		
        if(n==0)
        {
            return 1;
        }
        int ans=x*power(x,n-1);
        return ans;
	}
}

Thank you for reading this article so far, if you know some other way to write this program then you can leave a comment here or mail us at technonamecontact@gmail.com, So anyone can a get chance to publish their code on our website. As a result, one can improve knowledge and spread it to others

Please check most asked programming questions of strings with examples by clicking here, after that you might get a deep knowledge about string operations, in short, it will be helpful in clearing the interview.

You can also check other coding problems solved from the coding ninja’s platform here.

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

You can also follow us on Twitter for daily updates.

Leave a Reply

Your email address will not be published.