1. Member
Join Date
Feb 2011
Posts
2
Rep Power
0

## 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!

3. 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?

4. Why use a loop at all? A bit of simple math shows that:

Java 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

5. Member
Join Date
Feb 2011
Posts
2
Rep Power
0
*facepalm

JosAH u are the MAN!!!

THANK YOU!!! :D

6. 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:

Java 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•