Program to find sum of series 1²+2²+3²+….+n² in C; Through this tutorial, we will learn how to find sum of series 1²+2²+3²+….+n² using a standard formula, for loop, function, and recursion in c programs.
Programs to Find Sum of series 1²+2²+3²+….+n² in C
Let’s ise the following programs to find/evaluate the series 1^2+2^2+3^2+……+n^2 in c using for loop, standard formula, function and recursion:
- C Program to Find Sum of series 1²+2²+3²+….+n² using Standard Formula
- C Program to Find Sum of series 1²+2²+3²+….+n² using For Loop
- C Program to Find Sum of series 1²+2²+3²+….+n² using Function
- C Program to Find Sum of series 1²+2²+3²+….+n² using Recursion
C Program to Find Sum of series 1²+2²+3²+….+n² using Standard Formula
/* C Program to Calculate Sum of series 1²+2²+3²+....+n² */
#include <stdio.h>
int main()
{
int Number, Sum = 0;
printf("\n Please Enter any positive integer \n");
scanf(" %d",&Number);
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6;
printf("\n The Sum of Series for %d = %d ",Number, Sum);
}
The output of above c program; is as follows:
Please Enter any positive integer 10 The Sum of Series for 10 = 385
C Program to Find Sum of series 1²+2²+3²+….+n² using For Loop
#include <stdio.h>
int main()
{
int Number, i, Sum = 0;
printf("\nPlease Enter any positive integer \n");
scanf("%d",&Number);
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6;
for(i =1; i<=Number;i++)
{
if (i != Number)
printf("%d^2 + ",i);
else
printf("%d^2 = %d ",i, Sum);
}
}
The output of above c program; is as follows:
Please Enter any positive integer 10 1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2 + 10^2 = 385
C Program to Find Sum of series 1²+2²+3²+….+n² using Function
#include <stdio.h>
void Sum_Of_Series(int);
int main()
{
int Number;
printf("\n Please Enter any positive integer \n");
scanf("%d",&Number);
Sum_Of_Series(Number);
}
void Sum_Of_Series(int Number)
{
int i, Sum;
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6;
for(i =1;i<=Number;i++)
{
if (i != Number)
printf("%d^2 + ",i);
else
printf(" %d^2 = %d ", i, Sum);
}
}
The output of above c program; is as follows:
Please Enter any positive integer 5 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55
C Program to Find Sum of series 1²+2²+3²+….+n² using Recursion
#include <stdio.h>
int Sum_Of_Series(int);
int main()
{
int Number, Sum;
printf("\nPlease Enter any positive integer \n");
scanf("%d",&Number);
Sum=Sum_Of_Series(Number);
printf("\nSum of the Series = %d",Sum);
}
int Sum_Of_Series(int Number)
{
if(Number == 0)
return 0;
else
return (Number*Number) + Sum_Of_Series(Number-1);
}
The output of above c program; is as follows:
Please Enter any positive integer 5 Sum of the Series = 55