Function recursive power Learn programming Java

Lesson:

Functions


Exercise:

Function recursive power 46


Objetive:

Create a function that calculates the result of raising an integer to another integer (eg 5 raised to 3 = 53 = 5 × 5 × 5 = 125). This function must be created recursively.

An example of use would be: Console.Write( Power(5,3) );


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int number;
		int exponent;

		System.out.print("Base: ");
		number = Integer.parseInt(new Scanner(System.in).nextLine());
		System.out.print("Exponent: ");
		exponent = Integer.parseInt(new Scanner(System.in).nextLine());

		System.out.printf("%1$s^%2$s=%1$s" + "\r\n", Power(number, exponent));
	}

	public static int Power(int number, int exponent)
	{
		if (exponent == 0)
		{
			return 1;
		}
		else
		{
			return number * Power(number, exponent - 1);
		}
	}
}