Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

C Program to Find the Sum of First N Natural Numbers

Last Updated on May 15, 2023 by Prepbytes

Natural numbers are a subset of the real number system and range from 1 to infinity. It’s vital to notice that 0 is not included in natural numbers, often known as counting numbers. The sum of natural numbers can be calculated using programming, either by using the formula for the sum of natural numbers or by utilizing other programming techniques.

Approaches to Find the Sum of First N Natural Numbers

Here, we will discuss four different approaches to writing a C program to find the sum of first n natural numbers.

Approach 1: C Program to Find the Sum of First N Natural Numbers Using Formula

Two natural numbers that follow one another have a difference of 1. The progression of natural numbers is an arithmetic progression since every pair of subsequent numbers has the same difference. An arithmetic progression goes as follows: a, a+d, a+2d, a+3d,…, where a is the first element of the number and d is the difference between two succeeding numbers in the progression.

The following formula can be used to determine the sum of n numbers in an arithmetic progression,

Sn=(n∗(2a+(n−1)∗d))/2

where,

  • The series’ first term is a.
  • The common difference between any two terms in a series is called d.
  • The series number of terms is n.

The preceding formula can be further condensed into the equation for the sum of natural numbers, (n(n+1))/2, by substituting a=1 and d=1 in the equation.
The number of elements in the sequence is represented by the symbol n in the equation.

Program to Calculate the Sum of Natural Numbers Using Formula
It is possible to use the C programming language to implement the formula given in the previous section.

Example
The formula for calculating the sum of natural numbers can be used to generate the following code,

#include <stdio.h>
int main() {

   int natural_number;
   natural_number = 10;
   int sum;
// formula for the sum of natural numbers
   sum = natural_number*(natural_number+1)/2;
   printf("The Total Sum Of %d Natural Numbers Is: %d", natural_number, sum);
   return 0;
}

Output

The Total Sum Of 10 Natural Numbers Is: 55

Note: Due to the precedence of the operator in C, brackets are used in the formula surrounding (natural_number+1). Multiplication and division operations will be carried out before addition in C because they have a higher priority than addition and subtraction operations. We employ a bracket that takes precedence over other operators to stop this from happening.

Explanation
The code variable natural_number serves as an example of the sequence’s element count. The user provides this variable as input. The sum is obtained by changing the formula for the sum of natural numbers to reflect the number of elements in the sequence. The user is shown the output.

The program’s time complexity is O(1), or continuous time complexity.
The program’s space complexity is also O(1).

Approach 2: C Program to Find the Sum of First N Natural Numbers Using For Loop

The sum of natural numbers can be calculated by iterating through the numbers in the natural number sequence and adding them together using a for loop.

Example
There are two methods to use the for loop. The for loop in the program below iterates from 1 to a natural integer,

#include <stdio.h>
int main() {

   int natural_number;
   natural_number = 14;
   int sum=0;
   for(int i=1;i<=natural_number;i++){
    sum=sum+i;
   }
   printf("The total sum of %d natural numbers is %d", natural_number, sum);
   return 0;
}

The program below displays a for loop that iterates from the natural number to 1 (the first natural number in the sequence),

#include <stdio.h>

int main() {
   int natural_number;
   natural_number = 14;
   int sum=0;
// iterate from the maximum natural number to be summed to 1
   for(int i=natural_number;i>0;i--){
// summation of natural numbers
   sum=sum+i;
   }
   printf("The total sum of %d natural numbers is %d", natural_number, sum);
   return 0;
}

Output

The total sum of 14 natural numbers is 105

Explanation
The user provides the highest possible number in the natural number series. Iterating from 1 to the greatest natural number or from the greatest natural number to 1 are both possible with a for loop. The total sum of natural numbers is obtained by adding the sum at each iteration.

Both programs will have an O(n) time complexity, where n is the number of iterations the for loop performs. Both programs’ space complexity will be O(1).

Approach 3: C Program to Find the Sum of First N Natural Numbers Using Do While Loop

A do..while loop only checks for conditions from the second iteration of the loop’s run after running once without checking for the conditions it was given.

Example

#include <stdio.h>

int main() {
// total number of natural numbers to be summed
   int natural_number;
   natural_number = 13;
   int sum=0,i=1;
// do while loop 
    do
    {
// Summation of natural numbers
        sum = sum + i;
// increment i
        i++;		
    } while( i <= natural_number); // condition
   printf("The total sum of %d natural numbers is %d", natural_number, sum);
   return 0;
}

Output

The total sum of 13 natural numbers is 91

Explanation
The do..while loop multiplies the input number by each number starting at one. The user sees the outcome displayed.
The program has an O(n) time complexity, where n is the total number of iterations in the do…while loop. The program’s O(1) space complexity.

Approach 4: C Program to Find the Sum of First N Natural Numbers Using Recursion

A technique known as recursion involves repeatedly calling the same function. Finding the sum of natural numbers can be accomplished using recursion rather than loops.

Example

#include <stdio.h>

int Sum(int natural_no)
{
    if(natural_no != 0)
// recursive call to the same function
        return natural_no + Sum(natural_no - 1);
// return 0 if 'natural_no' is 0
    return 0;
}
int main() {
// total number of natural numbers to be summed
    int natural_number; 
    natural_number = 12;  
    printf("The total sum of %d natural numbers is %d", natural_number, Sum(natural_number));
 
    return 0;
}

Output

The total sum of 12 natural numbers is 78

Explanation
The input consists of the natural number. In a recursive function call, the same function is invoked with the parameter set to the value obtained by subtracting the number supplied as an argument in the previous function call. Only if the number decreases to zero will the recursive call terminate. At the conclusion of each function call, the output that the function returned is summed to obtain the sum of natural numbers.

The recursive natural number addition has an O(n) time complexity. A recursive function’s space complexity is influenced by how many function calls are made. The space complexity in the aforementioned example is O(n).

The functions will be called in the following order: Sum(12) –> Sum(11) –> Sum(10)…–> Sum(1).

The function returns zero once Sum(0) is achieved, and the output of each function is then added together backward to determine the sum,
Sum(0) –> Sum(1) –> Sum(2) …–> Sum(12), etc.

The return function and the accumulation are both executed in the same phase. When the function is Sum(0), the result is 0, and when the function is Sum(1), the result is 0+1, where 0 is the result of the Sum(0) function. To obtain the sum of n natural numbers, analogous accumulations are carried out for each succeeding function.

Summary

  • Natural numbers are also known as counting numbers since they begin at one.
  • The natural number series follows an arithmetic progression, hence the sum of natural numbers can be calculated using the sum of natural numbers formula, which is derived from arithmetic progression.
  • Iterative methods utilizing for, while, or do..while loops can also be used to calculate the sum of natural numbers.
  • A recurrence function can also be used to determine the sum of natural numbers.

FAQ related to the C Program to Find the Sum of First N Natural Numbers

Q1. Can we find the sum of first n natural numbers in O(1) time complexity?
Ans. Yes, there is one mathematical formula Sn​=(n∗(2a+(n−1)∗d))/2, by using it we can calculate the sum of first n natural numbers. We had discussed this approach in this article.

Q2. Can the formula for finding the sum of the first n natural numbers be used for negative values of n?
Ans. No, the formula is valid only for positive values of n. It does not work for negative values of n.

Q3. What are the first n natural numbers?
Ans. The first n natural numbers are the positive integers starting from 1 and going up to n.

Leave a Reply

Your email address will not be published. Required fields are marked *