C Program to Calculate the Sum of Natural Numbers Between Range

Lets write a C program to calculate sum of all natural numbers between the user entered range of numbers, using while loop.

We assume that user enters smaller number first and biggest number next.

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

Source Code: C Program to Calculate the Sum of Natural Numbers Between Range

 
#include < stdio.h >

int main()
{
    int min, max, sum = 0;

    printf("Enter 2 positive numbers\n");
    scanf("%d%d", &min, &max);

    printf("\n");

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

Output 1:
Enter 2 positive numbers
1
5
Sum = 15

Output 2:
Enter 2 positive numbers
10
15
Sum = 75

OR

 
#include < stdio.h >

int main()
{
    int min, max, sum = 0;

    printf("Enter 2 positive numbers\n");
    scanf("%d%d", &min, &max);

    printf("\n");

    while(min <= max)
    {
        sum = sum + min;
        printf("%d ", min);
        min++;

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

    return 0;
}

Output 1:
Enter 2 positive numbers
1
5

1 + 2 + 3 + 4 + 5 = 15

Output 2:
Enter 2 positive numbers
10
15

10 + 11 + 12 + 13 + 14 + 15 = 75

Output 3:
Enter 2 positive numbers
25
30

25 + 26 + 27 + 28 + 29 + 30 = 165

C Program to Calculate the Sum of Natural Numbers Between Range



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


Logic To Calculate the Sum of Natural Numbers Between Range

We ask the user to enter minimum and maximum number(i.e., the range) and we store it inside variable min and max. We check if variable min is less than or equal to max. Until this condition is true, while loop keeps iterating. Inside while loop we increment the value of min by one for each iteration. We also add the value of min to the value of sum on each iteration. At the end, when min is greater than max, control exits while loop and we printout the value of sum – which has the sum of all the numbers between the range entered by the user.

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