Java Program To Calculate Power of a Number Using While Loop
- May 26, 2020
- by
In this Java Program, we calculate the power of the number using while loop.
The Power (exponent) of the numbers says how many times to use the number in a multiplication. It is written in a small number right and above the base number.
E.g. the little 2 says to use 5 two times in a multiplication.
52 = 5 * 5 = 25
Logic : while(i!=0)
{
result *= number;
--i;
}
Step 1 : Create variable number and store the number 5 in it, similarly create variable p and store 2 in it.
Step 2 : Create variable result and store 1 in it.
Step 3 : Initialize i to p.
Step 4 : Apply the while loop
Step 5 : Do the multiplication and store the number into the variable result.
Step 6 : Decrement the i
Step 7 : Display the result by using System.out.print.
Program :
public class Power
{
public static void main(String[] args)
{
int number = 5, p = 2;
long result = 1;
int i = p;
while(i!=0)
{
result *= number;
--i;
}
System.out.println(number+"^"+p+ "="+result);
}
}
Output:
2^5 = 32
For the execution of the same do visit my YouTube Channel:


0 comments:
Post a Comment