Write a Java program to calculate the power of the given number. If we send two parameter (a,n) then it return an, but if we send one parameter (a) then it return a2.
Here, we use the function overloading procedure in java. Here, we create two methods called Power. First method with two parameters and another method with one parameter. But the name of the two methods are same.
import java.util.*; public class JavaPower { public int Power(int a) { return a*a; } public int Power(int a,int n) { int m=1; for(int i=0;i<n;i++) { m=m*a; } return m; } public static void main(String []args) { int a,n; Scanner sc=new Scanner(System.in); System.out.print("Enter A Number : "); a=sc.nextInt(); System.out.print("Enter A Power : "); n=sc.nextInt(); JavaPower jp=new JavaPower(); System.out.println( a + " Square = " + jp.Power(a)); System.out.print(a + " To The Power = " + n + “ : ” + jp.Power(a,n)); } }