power of a number in java | codeyourslf
Here you can learn how we can find the power of a number in java programming language with 3 different approaches.
Approach:-1 "java program to find power of a number using for loop"
import java.util.Scanner;
public class usingForLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base value: ");
int base = sc.nextInt();
System.out.println("Enter the exponent value: ");
int exponent = sc.nextInt();
int power = 1;
for(int i = 1; i <= exponent; i++){
power = power * base;
}
System.out.println("The power is: "+power);
}
}
Output
Approach:-2 "how to get power of a number using while loop"
import java.util.Scanner;
public class usingWhileLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base value: ");
int base = sc.nextInt();
System.out.println("Enter the exponent value: ");
int exponent = sc.nextInt();
int power = 1;
while(exponent != 0){
power = power * base;
exponent--;
}
System.out.println("The power is: "+power);
}
}
Approach:-3 "find power of a number using Math.pow() method"
import java.lang.Math;
import java.util.Scanner;
public class usingMathClass {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base value: ");
int base = sc.nextInt();
System.out.println("Enter the exponent value: ");
int exponent = sc.nextInt();
System.out.println("The power is: "+Math.pow(base,exponent));
}
}
Code Explanation
Here I am going to explain the above 3 approaches, those are used to find out the power of a number in java.
Approach:-1
We know 2 power 3 means we have to multiply '2', 3 times i.e 2*2*2 = 8.
To code this logic we can use for loop, for the above example, the loop will go 3 times and inside that loop we have to multiply the 2 one by one.
As a result 2 will be multiplied 3 times and the results will come 8 as the power.
Approach:-2
Here the logic will remain same and only difference is the loop. We have used while loop.
Approach:-3
Here I have used Math.pow() method to find the power of a number.
- In this program we don't need to write the logic, it is already written in the java.lang.Math class, we only have to use it.
- - Ex:- Math.pow(2,2) = 4.0
If you learn something new from this article please share with your friends .
- If you have any questions or any doubt please write down on the comment below 👇