Using Iteration, More on Basic Arithmetic Operations, More on Decision Statement
ID: 3823907 • Letter: U
Question
Using Iteration, More on Basic Arithmetic Operations, More on Decision Statements, and More on Writing Interactive Programs Definition 1 A power is an exponent to which a given quantity is raised. The expression r" is therefore known as "x to the nth power The power may be an integer, real number, or complex number In this project, you will use a loop to compute integer powers. The base can be any real number but the exponent will be an integer. Without the use of any standard Java Math library method, using only basic arithmetic operators and a loop, your program will compute powers with integer exponents considering the cases in the table. The code for the program should be optimized to avoid any unnecessary tests (comparisons) and local variables. See the table below: base (b) exponent (n 0 n is less than or equal to 0 indeterminate n is greater than 0 1 1 I-1 n is even I-1 n is odd 0 1 I b x b x b x x b n is positive factors b n is negative For the non-trivial cases, the last two rows of the table, when computing a power with a negative exponent, calculate the power using the positive exponent and then find its reciprocal.Explanation / Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Exponent {
public Exponent() {
}
public static void main(String[] args) {
int base;
int expo;
double value = 0;
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Base:");
base = Integer.parseInt(br.readLine());
System.out.println("Enter the Exponent:");
expo = Integer.parseInt(br.readLine());
if(base == 0){
//check1
if(expo <= 0){
value = Double.NaN;
}
//check2
else{
value = 0;
}
}
//check3
else if(base == 1){
value = 1;
}
//check4
else if( base == -1){
if(expo%2 == 0){
value = 1;
}
//check5
else{
value = -1;
}
}
//check6
else if(expo == 0){
value = 1;
}
//check7
else if(expo == 1){
value = base;
}
//check8
else if(expo == -1){
value = -base;
}
//check9
else{
int tempExpo = expo>0?expo:-1*expo;
value = 1;
while(tempExpo>0){
value = value*base;
tempExpo--;
}
//check10
if(expo<0){
value = 1/value;
}
}
System.out.println(base+" to the "+expo+" power is: "+value);
} catch (NumberFormatException | IOException e) {
System.out.println("Invalid Format!!");
}
}
}
Output:
Enter the Base:
3
Enter the Exponent:
-2
3 to the -2 power is: 0.1111111111111111
Enter the Base:
3
Enter the Exponent:
2
3 to the 2 power is: 9.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.