C Program to Calculate Sum of Natural Numbers

Positive integers 1, 2, 3, 4... are known as natural numbers. This program takes a positive integer from user( suppose user entered n ) then, this program displays the value of 1+2+3+....n.

Source Code to Calculate Sum of Natural Numbers


/* This program is solved using while loop. */

#include <stdio.h>
int main()
{
    int n, count, sum=0;
    printf("Enter an integer: ");
    scanf("%d",&n);
    count=1;
    while(count<=n)       /* while loop terminates if count>n */
    {
        sum+=count;       /* sum=sum+count */
        ++count;
    }
    printf("Sum = %d",sum);
    return 0;
}

Source Code to Calculate Sum Using for Loop


/* This program is solve using for loop. */

#include <stdio.h>
int main()
{
    int n, count, sum=0;
    printf("Enter an integer: ");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  /* for loop terminates if count>n */
    {
        sum+=count;                /* sum=sum+count */
    }
    printf("Sum = %d",sum);
    return 0;
}

Output

Enter an integer: 100
Sum = 5050

Both program above does exactly the same thing. Initially, the value of count is set to 1. Both program have test condition to perform looping iteration until condition count<=n becomes false and in each iteration ++count is executed. The only difference between for loop and while loop is the way of writing code.

This program works perfectly for positive number but, if user enters negative number or 0, Sum = 0 is displayed but, it is better is display the error message in this case. The above program can be made user-friendly by adding if else statement as:

/* This program displays error message when user enters negative number or 0 and displays the sum of natural numbers if user enters positive number. */

#include <stdio.h>
int main()
{
    int n, count, sum=0;
    printf("Enter an integer: ");
    scanf("%d",&n);
    if ( n<= 0)
        printf("Error!!!!");
    else
    {
       for(count=1;count<=n;++count)  /* for loop terminates if count>n */
       { 
          sum+=count;                    /* sum=sum+count */
       }
       printf("Sum = %d",sum);
    }
    return 0;
}

This program also can be solved using recursive function.

Similar Examples