C program to find sum of first n natural numbers

C program to find sum of first n natural numbers

This C program is to find the sum of first n natural numbers. Natural numbers are non-negative integers.

For eg if we take summation of 3 natural numbers 1,2,3 then their sum=6

Logic

Take a for loop starting with 0 keep incrementing the value of i and add it to the previous value.

Dry Run of the Program

Take input ‘n’ .Let us take n=3  //So it will give summation of 4 natural numbers

1st iteration   for(i=0;i<=n;i++) i.e.  for(i=0;i<=3;i++)

sum=sum+i    i.e sum = 0 + 0  hence sum=0

2nd iteration   for(i=1;i<=n;i++) i.e.  for(i=1;i<=3;i++)

sum=sum+i    i.e sum = 0 + 1  hence sum=1

3rd iteration   for(i=2;i<=n;i++) i.e.  for(i=2;i<=3;i++)

sum=sum+i    i.e sum = 1 + 2 hence sum=3

4th iteration   for(i=3;i<=n;i++) i.e.  for(i=3;i<=3;i++)

sum=sum+i    i.e sum = 3 + 3  hence sum=6

So output we get as sum = 6 for n=3.

Program

#include<stdio.h>
 
void main()
{
    int i,n,sum=0;
    printf("Enter how many terms you want to add\n");
    scanf("%d",&n);
    
    for(i=0;i<=n;i++)
    {
        sum=sum+i;
    }
    
    printf("Summation of first %d natural numbers = %d\n",n,sum);
}

Output

Share Me!