Write a method integerPower(base, exponent) that returns the value of base^expon
ID: 3596132 • Letter: W
Question
Write a method integerPower(base, exponent) that returns the value of base^exponent.
For example, integerPower(3, 4) returns 81. Assume that exponent is a positive nonzero integer, and base is an integer. Method integer should use for or while loop to control the calculation. Do not use any Math library methods. Incorporate this method into a program class and invoke this method with different combinations of input values at least 4 times. Please use printf statement to generate the multiple outputs from the sequence of the method invocations.
Explanation / Answer
Implemented th code as per the requirement. But it mentioned in the question that to ptintf, which will be there in C Programming language and also mentioned to incorporate into a class, but C prog language will not have classes. Code is written in C language. If you want it to be in some other language I can provied you. I'm proficient in C, C++, Java and Python.
Code:
------------
public class PowerCalculation {
public static void main(String[] args) {
System.out.println("Power = "+ integerPower(2,3));
System.out.println("Power = "+ integerPower(-2,3));
System.out.println("Power = "+ integerPower(2,-1));
System.out.println("Power = "+ integerPower(2,0));
}
public static int integerPower(int base, int exponent) {
int power = 1;
if(exponent<=0){
System.out.print("Invalid exponent ");
return -1; //Comment this if you want to exit the program for invalid inputs
//System.exit(0); You can un-comment this line for immediate exit for invalid input
}
//Calculating power
while(exponent>0){
power = power*base;
exponent--;
}
return power;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.