# Adding squared numbers in a loop

• 02-10-2011, 05:22 AM
kurap3ka
Adding squared numbers in a loop
ok ill try to explain my problem as best as i can.

Im required to create a program that sums up the squares beginning from 1 to the number the user entered, for example the number is 3 so the output will be 14 (because 1squared +2squared+ 3squared or 1+4+9=14)

so far here is what i got

int num;

System.out.println ("Please enter a number: ");

while (num <= 10){
num = 1*1+2*2+num*num;

i know it only prohibits me to only 3 but thats it!
• 02-10-2011, 05:36 AM
Junky
• 02-10-2011, 05:46 AM
Junky
OK, I'll go first.

The instruxctions say to add from 1 to num entered by user, so why does your loop go while num is less than 10?
• 02-10-2011, 08:11 AM
JosAH
Why use a loop at all? A bit of simple math shows that:

Code:

```// sum of squares up to n: int sos(int n) {   return n*(n+1)*(2*n+1)/6; }```
All those computer kids don't think anymore nowadays ... *grmbl*

kind regards,

Jos
• 02-10-2011, 08:58 AM
kurap3ka
*facepalm

JosAH u are the MAN!!!

THANK YOU!!! :D
• 02-10-2011, 09:13 AM
JosAH
Quote:

Originally Posted by kurap3ka
*facepalm

JosAH u are the MAN!!!

THANK YOU!!! :D

Doesn't your assignment text say that you have to use a loop? My code snippet doesn't use loops ... Oh well, the cat's out the bag already:

Code:

```int sos(int n) {   int sum= 0;   for (int i=1; i <= n; i++)       sum+= i*i;   return sum; }```
The above method does exactly the same as my previous little method. I prefer the first one over this silly loop version.

kind regards,

Jos