Breaking News

C Program to Calculate the Sum of Natural Numbers

Example #1: Sum of Natural Numbers Using for Loop

#include <stdio.h>
int main()
{
    int n, i, sum = 0;
    
    printf("Enter a positive integer: ");
    scanf("%d",&n);

    for(i=1; i <= n; ++i)
    {
        sum += i;   // sum = sum+i;
    }

    printf("Sum = %d",sum);

    return 0;
}

The above program takes the input from the user and stores in variable n. Then, for loop is used to calculate the sum upto the given number.

Example #2: Sum of Natural Numbers Using while Loop

#include <stdio.h>
int main()
{
    int n, i, sum = 0;
    
    printf("Enter a positive integer: ");
    scanf("%d",&n);

    i = 1;
    while ( i <=n )
    {
        sum += i;
        ++i;
    }

    printf("Sum = %d",sum);

    return 0;
}

Output

Enter a positive integer: 100
Sum = 5050

In both programs, the loop is iterated n number of times. And, in each iteration, the value of i is added to sum and i is incremented by 1.

Though both programs are technically correct, it is better to use for loop in this case. It’s because the number of iteration is known.

The above programs doesn’t work properly if the user enters a negative integer. Here’s a little modification of the above program to take input from the user until positive integer is entered.

Example #3: Program to Read Input Until User Enters a Positive Integer

#include <stdio.h>
int main()
{
    int n, i, sum = 0;

    do {
        printf("Enter a positive integer: ");
        scanf("%d",&n);
    }
    while (n <= 0);

    for(i=1; i <= n; ++i)
    {
        sum += i;   // sum = sum+i;
    }

    printf("Sum = %d",sum);

    return 0;
}

Leave a Reply

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

*

Scroll To Top