Java Program to Find Power of a Number

This is a java program to calculate power of a given number. The inputs are the number and its exponent (power). For example, if you give m and n, the result is m^n. You may use built-in function Math.pow() or hard code it.

Using Built-in Function

import java.util.Scanner;

public class Power{

public static void main(String[] args)
{
int m,n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number and its power");
m=sc.nextInt();
n=sc.nextInt();
System.out.printf("m^n = %.0f",(float)Math.pow(m,n));
}
}

Without using Built-in function

import java.util.Scanner;

public class Power{

public static void main(String[] args)
{
int m,n,i,p=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number and its power");
m=sc.nextInt();
n=sc.nextInt();
for(i=0;i<n;i++)
    p*=m;
System.out.printf("m^n = %d",p);
}
}

No comments:

Post a Comment