Hello I need some help.
How do I use for loop in order to calculate the power of a number?
In here, I used Math.pow and I need to change it and use for loop instead.
import java.util.Scanner; public class LoopActivity { public static void main(String[] args) { /*------------------------------------------*/ Scanner scanner = new Scanner(System.in); int loopRange = 0, sumOdd = 0, sumEven = 0, n1 = 1, n2 = 2, x1 = 1; /*------------------------------------------*/ //if loopRange is less than 0 the loop doesn't work. do { System.out.print("Please enter loop range: "); loopRange = scanner.nextInt(); if(loopRange < 0) { System.out.println("\nError: Invalid loop range.\n\tPlease enter a number equal or grater than 0.\n"); } } while(loopRange < 0); for(int x2 = loopRange/2 ; n1 <= loopRange ; x2--, x1++) { //odd int ans1 = (int) Math.pow(n1, x1); System.out.println(n1 + "^" + x1 + "=" + ans1); sumOdd += ans1; n1 += 2; //even if(n2 <= loopRange) { int ans2 = (int) Math.pow(n2, x2); System.out.println(n2 + "^" + x2 + "=" + ans2); sumEven += ans2; n2 += 2; } } System.out.println("The sum of ODD increasing power is: " + sumOdd); System.out.println("The sum of EVEN decreasing power is: " + sumEven); } }