Sum of Cube of 'n' Numbers || Taking Value from User || C++





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();
}

  
The Code given below can be used in g++/gcc Compiler.

// 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

Previous Post Next Post