Â
In this, we are going to find the sum of cubes of first n natural numbers in a C++ program.
Eg :
sum of cubes of first 5 natural numbersÂ
1^3Â + 2^3Â + 3^3Â + 4^3Â + 5^3Â = 1 + 8 + 27 + 64 + 125 = 225
This can be found using formula (n*(n+1)/2)^2Â where n = 5
(5*(5+1)/2)^2Â
= (5*(6)/2)^2Â Â
= (15)^2
= 225
We will solve it using C++
The Code given below can be used in Turbo C++ Compiler.
// sum of cubes of first n natural numbers
#include<iostream.h>
#include<conio.h>
#include <math.h>
void main()
{
clrscr();
int n ;
cout<<"Enter positive integer value of n to find sum of cube of n natural numers...\n";
cin>>n;
int sum = pow((n*(n+1)/2.0),2);
cout<<"Sum of cube of "<<n<<" natural numbers = "<<sum;
getch();
}
// sum of cubes of first n natural numbers
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n ;
cout<<"Enter positive integer value of n to find sum of cube of n natural numers...\n";
cin>>n;
int sum = pow((n*(n+1)/2.0),2);
cout<<"Sum of cube of "<<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