Kasper Kasper - 2 months ago 17
Java Question

Java for-loop to the power

import static java.lang.Math.pow;

class projectThreeQ2{
public static void main (String args[]){

//Q2: Write a for statement to compute the sum 1 + 2^2 + 32 + 42 + 52 + ... + n2.

int n = 7;
int sum = 0;

for (int i = 0; i < n; i++){
sum = sum + (int)Math.pow(n,2);
}

System.out.println(sum);
}
}


The question is to make a for-loop to the sum of the n^2.

So in my case;
1
4
9
16
25
36.
Which is equal to 91. However, when I run my code I get 343. Why?

Answer

You are using the wrong variable inside the for-loop. You use n instead of i. The correct code is:

for (int i = 1; i <= n; i++){
    sum = sum + (int)Math.pow(i,2);
}

Edited because the loop should run from 1 to n (inclusive) according to the question statement.

Comments