# Sum of Squares of N Natural Numbers in C

Previously we have written a program to find the sum of N natural numbers in C, now we will write the program for the sum of squares of first N natural numbers in C using while loop, for loop, and without loop.

Prerequisites:-

Sum of squares of first N natural numbers is given as = `12 + 22 + 32 + 42 + ...... + (n-1)2 + n2`

To find the sum of the squares of N natural numbers declare a variable and initialize it with value 1. Declare another variable sum and initialize it with 0. Now, in every iteration increase sum value until the value N.

## Sum of squares of N natural numbers in C using for loop

``````#include<stdio.h>
int main()
{
int n, sum=0;

printf("Enter n value: ");
scanf("%d", &n);

for(int i=0; i<=n; i++)
{
sum += (i*i);
}

printf("Sum of squares of first %d natural numbers = %d",
n, sum);

return 0;
}``````

Output for the different test-cases:-

Enter n value: 5
Sum of squares of first 5 natural numbers = 55

Enter n value: 10
Sum of squares of first 10 natural numbers = 385

In this program, the variable n store the value of the number that is entered by the user. Similarly, the variable sum store the result.

The sum of squares of n natural numbers also can be calculated in reverse order from the previous one. For example, the sum of squares of first N natural numbers is given as = n2 + (n-1)2 + … + 32 + 22 + 12

In this case, the loop control variable should initialize with “n” and the decrement operator should be used. Below program shows it,

``````#include<stdio.h>
int main()
{
int n, sum=0;

printf("Enter n value: ");
scanf("%d", &n);

for(int i=n; i>=0; i--)
{
sum += i*i;
}

printf("Sum of squares of first %d natural numbers = %d",
n, sum);

return 0;
}``````

## Using while loop

``````#include<stdio.h>
int main()
{
int n, sum=0, i=0;

printf("Enter n value: ");
scanf("%d", &n);

while(i<=n)
{
sum += (i*i);
i++;
}

printf("Sum of squares of first %d natural numbers = %d",
n, sum);

return 0;
}``````

## Without using a loop

We can also find the sum of squares of N natural numbers without using the loop. The formula is given as,

The sum of squares of N natural numbers = n(n+1)(2n+1)/6;

``````#include<stdio.h>
int main()
{
int n;

printf("Enter n value: ");
scanf("%d", &n);

int sum = n*(n+1)*(2*n+1)/6;

printf("Sum of squares of first %d natural numbers = %d",
n, sum);

return 0;
}``````

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!