Thursday 21 August 2014

Filled Under: ,

C Program to Calculate Sum of Natural Numbers

Share


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.

Example of C Program to Calculate Sum of Natural Numbers

Program 1


/* 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;
}

Program 2


/* 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