Write a Java program to calculate power of a number without using Operators


This Java program calculates the power of a number entered by the user. It takes two integer inputs from the user, the base number and the exponent, using the Scanner class.

  • If both the base and exponent are positive numbers, the program calls the power() function to calculate the power of the number. Otherwise, the program displays a message asking the user to enter positive numbers.
  • The power() function takes two integer arguments, b and e, which represent the base and exponent of the number, respectively. It uses a nested loop to calculate the power of the number.
  • The outer loop iterates from 1 to e-1, while the inner loop iterates from 1 to b-1. The variable res holds the result of each multiplication, and the variable t holds the previous value of res for the next multiplication.
  • At the end of the function, res holds the final result of the power calculation, which is then returned.

Overall, this program calculates the power of a number entered by the user using the power() function and displays the result.

Source Code

import java.util.*;
public class Calculate_Power
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Base Number : ");
		int base = input.nextInt();
		System.out.print("Enter the Exponent Number : ");
		int exp = input.nextInt();
		if (base > 0 && exp > 0 )
			System.out.println("Power of the number: "+power(base, exp));
		else
			System.out.println("Please Enter the Positive Numbers..");
	}
	public static int power(int b, int e)
	{
		if (e == 0)
			return 1;              
		int res = b;
		int t = b;
		int i, j;          
		for (i = 1; i < e; i++)
		{
			for (j = 1; j < b; j++)
			{
				res += t;
			}
			t = res;
		}
		return res;
	}
}

Output

Enter the Base Number : 5
Enter the Exponent Number : 3
Power of the number: 125

Example Programs