Reputation: 49
Doing an assignment for my computer science class and can't quite figure out what I'm doing wrong. I have to write a program that adds all the squares between 1 and 100 (1, 4, 9, 16, 25, 36, 49, 64, 81, 100) As part of the assignment I'm required to use a "while" statement, so no "for" statements will help. My current code is as follows.
import java.util.Scanner;
public class While42B {
public static void main(String []args ) {
Scanner reader = new Scanner(System.in);
int n = 1;
int sum = 0;
while (n <= 100) {
n = (n*n);
n++;
sum = (sum + n);
}
System.out.println(sum);
}
}
And the return I get from the GUI is
710
Any help would be greatly appreciated, thank you!
Upvotes: 3
Views: 39608
Reputation: 1
Simply read the mathematics and then proceed to translate the mathematical operations into code. I've worked out the mathematics which I hope could help you. I have also provided an answer to the question stated by your professor, I do hope that I am able to have been helpful in your arrangements. No credit needed except to Carl Friedrich Gauss.
X(nsquared base 1 + nsquared base n) divided by 2
X equals number of numbers (100) and n base 1 equals first number (1) and n base n equals last number (100), I did not include the squares in the numerical description but you do need too include squares in the first and last number. 1 squared and 100 squared.
Upvotes: -1
Reputation: 559
If you want to do it in your way I mean first square the value of each number,keep it in a variable and add it to the sum you can use a different variable
instead of n
to store the square value of each number like this :
int n = 1;
int squareValue;
int sum = 0;
while (n <= 10) {
squareValue= (n*n);
sum += squareValue;
n++;
}
System.out.println(sum);
Upvotes: 4
Reputation: 39437
I realize you're looking for a while loop but
just FYI you can use the direct formula:
System.out.println( n * (n + 1) * (2 * n + 1) / 6);
Upvotes: 9
Reputation: 3023
Just as an add-on, in Java 8, one can do the sum of squares of first 10 natural numbers as follows:
int sum = IntStream.rangeClosed(1, 10).map(n -> n * n).sum();
Upvotes: 5
Reputation: 41271
Look at this statement:
n = (n*n);
You're squaring n
inside the loop, and then incrementing it. Do the following instead:
while (n <= 10) {
sum = (sum + (n*n));
n++;
}
This way, you don't modify n
by squaring it, and you can properly track its value for the while loop.
Upvotes: 13
Reputation: 7769
You are changing the value of n in: n= n*n So now you are not looping from 1 to 100, you are skipping a lot of numbers
Upvotes: 3