Hello I am new in nested looping and I need help with my nested for loop assignment, Here's the instruction and what I have done so far:
Create a Java program that accepts integer input from the user. Loop the input until to the last value. Generate a power value of each value from the range of input. For odd numbers, the power value is increasing range from 1 to the last odd number. For the even numbers, the power value is decreasing starts from the total of even numbers until 1.
Example:
The value input from the user is 6.
The program displays the range with corresponding power and total.
1^1=1---------------- ODD (1x1=1)------------Power of 1 - for odd is increasing
2^3=8---------------- EVEN (2x2x2=8)---------Power of 3 - for even is decreasing
3^2=9---------------- ODD (3x3=9)------------Power of 2 - for odd is increasing
4^2=16--------------- EVEN (4x4=16)----------Power of 2 - for even is decreasing
5^3=125------------- ODD (5x5x5=125)-------Power of 3 - for odd is increasing
6^1=6---------------- EVEN (6x1=6)------------Power of 1 - for even is decreasing
The sum of ODD increasing power is: 135 ( 1+9+125 = 135) - sum all the odd results.
The sum of EVEN decreasing power is: 30 (8+16+6=30) - sum all the even results.
int loopRange = scanner.nextInt(); int sumOdd = 0, sumEven = 0; for(int x = 1; x <= loopRange; x++){ if (x % 2 == 1){ int base = x; int ansOdd = 1; int y; for(y = 1; y <= 3 ; y++){ ansOdd *= base; sumOdd += ansOdd; } System.out.println(base + "^" + y + "=" + ansOdd); } else if (x % 2 == 0){ int base = x; int ansEven = 1; int y; for(y = 3; y <= 1; y--){ ansEven *= base; sumEven += ansEven; } System.out.println(base + "^" + y + "=" + ansEven); } } System.out.println("The sum of ODD increasing power is: " + sumOdd); System.out.println("The sum of EVEN decreasing power is: " + sumEven); } }
The output is this:
Please enter loop range: 10
1^4=1
2^3=1
3^4=27
4^3=1
5^4=125
6^3=1
7^4=343
8^3=1
9^4=729
10^3=1
The sum of ODD increasing power is: 1415
The sum of EVEN decreasing power is: 0
But I want the output to be like this:
Please enter loop range: 10
1^1=1
2^5=32
3^2=9
4^4=256
5^3=125
6^3=216
7^4=2401
8^2=64
9^5=59049
10^1=10
The sum of ODD increasing power is: 61581
The sum of EVEN decreasing power is: 578