 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
C Program for cube sum of first n natural numbers?
In this problem we will see how we can get the sum of cubes of first n natural numbers. Here we are using one for loop, that runs from 1 to n. In each step we are calculating cube of the term and then add it to the sum. This program takes O(n) time to complete. But if we want to solve this in O(1) or constant time, we can use this series formula −

Algorithm
cubeNNatural(n)
begin sum := 0 for i in range 1 to n, do sum := sum + i^3 done return sum end
Example
#include<stdio.h> long cube_sum_n_natural(int n) {    long sum = 0;    int i;    for (i = 1; i <= n; i++) {       sum += i * i * i; //cube i and add it with sum    }    return sum; } main() {    int n;    printf("Enter value of n: ");    scanf("%d", &n);    printf("Result is: %ld", cube_sum_n_natural(n)); } Output
Enter value of n: 6 Result is: 441
Advertisements
 