Â
In this, we are going to find the sum of squares of first n natural numbers in a C++ program.
Eg :
sum of squares of first 5 natural numbersÂ
1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 1 + 4 + 9 + 16 + 25 = 55
This can be found using formula n*(n+1)*(2*n+1)/6 where n = 5
5*(5+1)*(2*5 + 1)/6 = 5*6*11/6 = 55
We will solve it using C++
The Code given below can be used in Turbo C++ Compiler.
// sum of squares of first n natural numbers #include<iostream.h> #include<conio.h> void main() { clrscr(); int n ; cout<<"Enter positive integer value of n to find sum of squares of n natural numbers...\n"; cin>>n; int sum = n*(n+1)*(2*n+1)/6; cout<<"Sum of square "<<n<<" natural numbers = "<<sum; getch(); }
// sum of squares of first n natural numbers
#include <iostream>
using namespace std;
int main()
{
int n ;
cout<<"Enter positive integer value of n to find sum of squares of n natural numbers...\n";
cin>>n;
int sum = n*(n+1)*(2*n+1)/6;
cout<<"Sum of square "<<n<<" natural numbers = "<<sum;
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP