C Program to Calculate the Sum of Natural Numbers From 1 to N

Lets write a C program to calculate sum of all natural numbers from 1 to N, using while loop.

Related Read:
while loop in C programming
C Program to Print Natural Numbers from 1 to N using While loop
C Program to Print Natural Numbers Between Two Numbers using While loop

Source Code: C Program to Calculate the Sum of Natural Numbers From 1 to N

 
#include < stdio.h >

int main()
{
    int num, count = 1, sum = 0;

    printf("Enter a positive number\n");
    scanf("%d", &num);


    while(count <= num)
    {
        sum = sum + count;
        count++;
    }
    printf("Sum = %d\n", sum);
    return 0;
}

Output 1:
Enter a positive number
5
Sum = 15

Output 2:
Enter a positive number
10
Sum = 55

OR

 
#include < stdio.h >

int main()
{
    int num, count = 1, sum = 0;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    printf("Sum of natural numbers from 1 to %d is:\n", num);
    while(count <= num)
    {
        sum = sum + count;
        printf("%d  ", count);
        count++;

        if(count > num)
        {
            printf(" = %d\n", sum);
        }
        else
        {
            printf("+ ");
        }

    }
    return 0;
}

Output 1:
Enter a positive number
5
Sum of natural numbers from 1 to 5 is:
1 + 2 + 3 + 4 + 5 = 15

Output 2:
Enter a positive number
10
Sum of natural numbers from 1 to 10 is:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

C Program to Calculate the Sum of Natural Numbers From 1 to N



YouTube Link: https://www.youtube.com/watch?v=PwZgujbXWz4 [Watch the Video In Full Screen.]


Logic To Calculate the Sum of Natural Numbers From 1 to N

We ask the user to enter a positive number and store it in variable num. We assign 1 to variable count and 0 to variable sum.

In while loop we check for the condition: count is less than or equal to num. While loop keeps executing until that condition is true. Inside while loop we increment the value of count by one and also add the value of count to the previous value of sum. We keep doing this until count is less than or equal to num. Once that condition is false, control exits the while loop and we display the value of sum as output.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert