The Wayback Machine - https://web.archive.org/web/20240721032525/https://www.geeksforgeeks.org/c-program-to-calculate-sum-of-natural-numbers/
Open In App

C Program to Calculate Sum of Natural Numbers

Last Updated : 27 Jan, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

 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

C




// C Program to demonstrate
// Sum of Natural Numbers
// using while loops
 
#include <stdio.h>
int main()
{
    int i, s = 0;
    int n = 10;
    i = 1;
   
    // while loop executes
    // the statements until the
    // condition is false
    while (i <= n) {
       
        // adding natural numbers
        // up to given number n
        s += i;
        i++;
    }
    // printing the result
    printf("Sum = %d", s);
    return 0;
}


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.

C




// C Program to demonstrate
// Sum of Natural Numbers
// using for loops
#include <stdio.h>
 
int main()
{
 
    int i, s = 0;
    int n = 10;
 
    for (i = 0; i <= n; i++) {
       
        // adding natural numbers
        // up to given number n
        s += i;
    }
   
    // printing the result
    printf("Sum = %d", s);
    return 0;
}


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

C




// C Program to demonstrate
// Sum of Natural Numbers
// using recursion
#include <stdio.h>
 
int sumofnaturalnumbers(int num)
{
    if (num != 0)
       
        // adding natural numbers up to given number n
        return num + sumofnaturalnumbers(num - 1);
    else
        return num;
}
 
int main()
{
 
    int number = 10;
   
    // printing the result
    printf("Sum = %d", sumofnaturalnumbers(number));
   
    return 0;
}


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

C




// C Program to demonstrate
// Sum of Natural Numbers
// using functions
#include <stdio.h>
 
int sumofnaturalnumbers(int num)
{
    int i, s = 0;
    for (i = 0; i <= num; i++) {
       
        // adding natural numbers
        // up to given number n
        s += i;
    }
    // printing the result
    printf("Sum = %d", s);
}
 
int main()
{
 
    int number = 10;
   
    // calling the function
    sumofnaturalnumbers(number);
    return 0;
}


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

C




// C Program to demonstrate
// Sum of Natural Numbers
#include <stdio.h>
int main()
{
 
    int num = 10;
     
    int s,x;
    s=num*(num+1);
    x=(int)(s/2);
    printf("Sum = %d", x);
    return 0;
}


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.



Similar Reads

C Program to Find Sum of Natural Numbers using Recursion
Natural numbers include all positive integers from 1 to infinity. There are multiple methods to find the sum of natural numbers and here, we will see how to find the sum of natural numbers using recursion. Example Input : 5Output : 15Explanation : 1 + 2 + 3 + 4 + 5 = 15 Input : 10Output : 55Explanation : 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
2 min read
C Program for cube sum of first n natural numbers
Write a C program to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till the n-th term. Examples: Input: n = 5Output: 225Explanation: 13 + 23 + 33 + 43 + 53 = 225 Input: n = 7Output: 784Explanation: 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784 C Program for cube sum of first n natural numbers using Naive Approach:Define the function sumOfCubes()
4 min read
Program to calculate area of a Tetrahedron
A tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom of the base, and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The area of the Tetrahedron can be found by using t
5 min read
Program to calculate First and Follow sets of given grammar
Before proceeding, it is highly recommended to be familiar with the basics in Syntax Analysis, LL(1) parsing, and the rules of calculating First and Follow sets of a grammar. Introduction to Syntax AnalysisWhy First and Follow?FIRST Set in Syntax AnalysisFOLLOW Set in Syntax Analysis Assuming the reader is familiar with the basics discussed above,
8 min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
C Program to Calculate the Average of All Elements of an Array
Given an array arr of size N, the task is to calculate the average of all the elements of the given array. Example Input: arr[] = {1, 2, 3, 4, 5} Output: 3Approach 1. We can simply find the sum of all elements of a given array. 2. Divide this sum by the total number of elements present in the array. Sum of the elements is = 1+2+3+4+5 = 15 The total
2 min read
C Program to Find the Sum of Fibonacci Numbers at Even Indexes up to N Terms
Here, we will build a C Program to Find the Sum of Fibonacci numbers at even indexes up to N terms Fibonacci Numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …… Input: N = 5 Output: 88 // Sum of the elements at even indexes = 0 + 1 + 3 + 8 + 21 + 55 = 88Approach:This approach includes solving the problem directly by finding all Fibonacci numb
2 min read
C Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers)
Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples :  Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7 Output: Sum found between indexes 1 a
5 min read
C Program to Check Whether a Number Can Be Express as Sum of Two Prime Numbers
Prime numbers are numbers that have only 2 factors, 1 and themselves. For example, 2, 3, 5, 7, 11, etc are some of the first prime numbers. Here we will see whether a number can be expressed as the sum of two prime numbers using a C program. Example Input: 7Output: YesExplanation: 7 can be expressed as sum of 2 and 5 which are prime Input: 11Output
2 min read
Sorting integer data from file and calculate execution time
Prerequisite: Selection Sort In this article, we are going to apply selection sort algorithm, in which the source of input is A FILE CONTAINING 10000 INTEGERS and output will be the total time taken to sort. Important functions to be used: rand(): Used to generate random numbers. fopen(): Used to open file . fscanf(): Used to scan data from file .
3 min read
three90RightbarBannerImg