C Program to Find the Sum of Natural Numbers

The positive numbers such as 1,2,3,4,5…. etc are known as natural numbers.

In this program, you will see how to calculate the sum up to n natural numbers. We will ask a user to enter a number and then calculate the sum up to that number.

For example, if the user enters 5, then we will calculate 1+2+3+4+5.

To understand this program better you should have the knowledge of –

  • Loops.
  • Assignment Operators.

Program using for loop

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

    if(num > 0)
    {
        for (i = 1; i <= num; i++)
        {
            sum += i; //sum = sum + i
        }
        printf("The sum is %d ", sum);
    }
    else
    {
        printf("You have entered an invalid number");
    }
    return 0;
}

Output

Enter a positive number:10

The sum is 55

Program using while loop

#include <stdio.h>
int main()
{
    int num, i = 1, sum = 0;
    printf("Enter a positive number: ");
    scanf("%d", &num);
    if(num > 0)
    {
        while (i <= num)
        {
            sum += i; //sum = sum + i
            i++;
        }
        printf("The sum is %d ", sum);
    }
    else
    {
        printf("You have entered an invalid number");
    }
    return 0;
}

Output

Enter a positive number:100

The sum is 5050

Explanation

  • In both the programs, we have declared three variables num, i, and sum. The sum is also initialized with 0.
  • The variable num will store the number entered by the user. The variable i is used as a counter for the loop.
  • The loop would execute from 1 to the number stored inside ‘num’. So, for instance, if the user enters 10, the loop will run 10 times from 1 to 10.
  • We have put an if-else block to check if the user has entered a positive number. If the number is positive, the control will enter the loop block and the sum would be generated, else a message would be shown “You have entered an invalid number”.
  • Every time the loop runs, the value of sum is incremented by the current value of i.

In the first iteration sum += i// sum += 1 // Sum is storing 1

In the first iteration sum += i// sum += 2 // Sum is storing 3

In the first iteration sum += i// sum += 1 // Sum is storing 6

and so on.

You can be more specific by placing an if-else if-else block.

Program

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

    if(num > 0)
    {
        while (i <= num)
        {
            sum += i; //sum = sum + i
            i++;
        }
        printf("Sum = %d", sum);
    }
    else if(num == 0)
    {
        printf("You have entered 0");
    }
    else
    {
        printf("You have entered a negative number");
    }

    return 0;
}