
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program for cube sum of first n natural numbers in C++
Given an integer n, the task is to find the sum of the cube of first n natural numbers. So, we have to cube n natural numbers and sum their results.
For every n the result should be 1^3 + 2^3 + 3^3 + …. + n^3. Like we have n = 4, so the result for the above problem should be: 1^3 + 2^3 + 3^3 + 4^3.
Input
4
Output
100
Explanation
1^3 + 2^3 + 3^3 + 4^3 = 100.
Input
8
Output
1296
Explanation
1^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 +8^3 = 1296.
Approach used below is as follows to solve the problem
We will be using simple iterative approach in which we can use any loop like −forloop, while-loop, do-while loop.
Iterate i from 1 to n.
For every i find it’s cube.
Keep adding all the cubes to a sum variable.
Return the sum variable.
Print the results.
Algorithm
Start Step 1→ declare function to calculate cube of first n natural numbers int series_sum(int total) declare int sum = 0 Loop For int i = 1 and i <= total and i++ Set sum += i * i * i End return sum step 2→ In main() declare int total = 10 series_sum(total) Stop
Example
#include <iostream> using namespace std; //function to calculate the sum of series int series_sum(int total){ int sum = 0; for (int i = 1; i <= total; i++) sum += i * i * i; return sum; } int main(){ int total = 10; cout<<"sum of series is : "<<series_sum(total); return 0; }
Output
If run the above code it will generate the following output −
sum of series is : 3025
- Related Questions & Answers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- C Program for the cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- C++ Program for Sum of squares of first n natural numbers?
- Sum of first n natural numbers in C Program
- Python Program for Sum of squares of first n natural numbers
- Sum of sum of first n natural numbers in C++
- Sum of squares of first n natural numbers in C Program?
- Program to find sum of first n natural numbers in C++
- Sum of square-sums of first n natural numbers
- 8085 program to find the sum of first n natural numbers
- Java Program to calculate Sum of squares of first n natural numbers
- Finding sum of first n natural numbers in PL/SQL
Advertisements