Computer Applications
Write a program that uses a method power( ) to raise a number m to power n. The method takes int values for m and n and returns the result correctly. Use a default value of 2 for n to make the function calculate squares when this argument is omitted. Write a main( ) method to get the value of m and n to display the calculated result.
Java
User Defined Methods
9 Likes
Answer
import java.util.Scanner;
public class KboatCalcPower
{
public double power(int m) {
double pow = Math.pow(m,2);
return pow;
}
public double power(int m, int n) {
double pow = Math.pow(m,n);
return pow;
}
public static void main(String args[]) {
KboatCalcPower obj = new KboatCalcPower();
Scanner in = new Scanner(System.in);
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
double res = obj.power(m,n);
System.out.println("m^n = " + res);
res = obj.power(m);
System.out.println("Omitting n");
System.out.println("m^2 = " + res);
}
}
Variable Description Table
Program Explanation
Output

Answered By
3 Likes
Related Questions
Write a function that takes two char arguments and returns 0 if both the arguments are equal. The function returns -1 if the first argument is smaller than the second and 1 if the second argument is smaller than the first.
Write a complete Java program that invokes a function satis() to find whether four integers a, b, c, d sent to satis( ) satisfy the equation a3 + b3 + c3 = d3 or not. The function satis( ) returns 0 if the above equation is satisfied with the given four numbers otherwise it returns -1.
How does the compiler interpret more than one definitions having same name ? What steps does it follow to distinguish these ?
Discuss how the best match is found when a call to an overloaded method is encountered. Give example(s) to support your answer.