VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-calculate-sum-of-natural-numbers/

⇱ C Program to Calculate Sum of Natural Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Calculate Sum of Natural Numbers

Last Updated : 27 Jan, 2023

 Here we will build a C program to calculate the sum of natural numbers using 4 different approaches i.e.

  1. Using while loop
  2. Using for loop
  3. Using recursion
  4. Using Functions

We will keep the same input in all the mentioned approaches and get an output accordingly.

Input: 

n = 10

Output: 

55 

Explanation: The sum of natural numbers up to a given number is 0+1+2+3+4+5+6+7+8+9+10=55

Approach 1: Using while loop 

The while loop executes the statements until the condition is false


Output
Sum = 55

Time Complexity : O(n) as the loop runs for n iterations
Auxiliary Space : O(1) as only a fixed amount of memory is used.

Approach 2: Using for loop

For loop iterates up to n number of times.


Output
Sum = 55

Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.

Approach 3: Using recursion


Output
Sum = 55

Time Complexity : O(n) as the function is called n+1 times.
Auxiliary Space : O(n) as each function call stores one value in the call stack, which consumes memory.

Approach 4: Using functions


Output
Sum = 55

Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.

Approach 5 : Using the formula sum of n natural numbers = n*(n+1)/2


Output
Sum = 55

Time Complexity : O(1) as it performs a fixed number of operations regardless of the input size.
Auxiliary Space : O(1) as only a fixed amount of memory is used.

Comment
Article Tags: