
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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
- Related Articles
- C++ Program for cube sum of first n natural numbers?
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- Python Program for cube sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Swift Program to Calculate 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 squares of first n natural numbers in C Program?
- Program to find sum of first n natural numbers in C++
- Sum of sum of first n natural numbers in C++
- Java Program to Display Numbers and Sum 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

Advertisements