# Thread: How to print This series?

1. ## How to print This series?

Hello,

Here I have a question that how to print the sum (answer) of the following series using loops in C:

12+22+32+42+52+62+......+n2

"n" is the given range of series by the user(input). 2. Are you aware of the for loop?
Here is an example.
Code:
```int i;
int sum = 0;
for(i = 0 ; i < 50 ; i++)
{
sum += i*5;
}
printf("sum is %d\n", sum);```
This will give the sum of
5*1 + 5*2 + ... + n*5
I think I already said too much  3. I'm still trying to figure out the pattern. The fifth term is bugging me. 4. Originally Posted by whiteflags I'm still trying to figure out the pattern. The fifth term is bugging me.
Nice observation...

shansajid did you miss a 4²? If not, then you could easily bypass this term..but I think you missed it :P 5. oh sorry i missed. edited.... 6. Originally Posted by shansajid oh sorry i missed. edited....
No problem Whiteflags is too good to miss something ;p
Have you come up with some code?  7. std10093, Im trying this code that you shared but its output is wrong. Whats the matter with this code?

Code:
```
#include <stdio.h>
#include <conio.h>

void main()
{
clrscr();

int a,n,sum;
printf("\nEnter the range: ");
scanf("%d", &n);

for(a=0; a<=n; a++)
{
sum += a*a;
}
printf("%d", sum);

getch();
}``` 8. Perhaps you should initialise sum to 0 to begin with. 9. Take again a look in my example. There are two things that are different  10. your code shows that 5 is multiplied in all elements of a series. but i replaces usually 5 by the current element which is going to multiplied.  11. yes sum=0, now its running correct 12. Good move!

But, as Salem already said, I have initialized a variable... Also my for loop is a little different  13. Originally Posted by shansajid yes sum=0, now its running correct
Oh... Take a look at Salem's avatar (picture). 14. Thankyou std10093 and Salem for your help 15. Works for me - post your evidence.
Code:
```\$ cat foo.c
#include <stdio.h>

int main()
{
int a,n,sum = 0;
printf("\nEnter the range: ");
scanf("%d", &n);

for(a=0; a<=n; a++)
{
sum += a*a;
}
printf("%d\n", sum);
return 0;
}
\$ gcc foo.c
\$ ./a.out

Enter the range: 5
55
\$``` Popular pages Recent additions 