C Program To Calculate Sum of Natural Numbers Between Range using For Loop


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

We check if the user has entered smaller number first and then the larger number. If not, we swap the numbers present in the variables min and max.

Related Read:
For Loop In C Programming Language
C Program To Print Natural Numbers Between Two Numbers using for loop
Swap 2 Numbers Using a Temporary Variable: C

Video Tutorial: C Program To Calculate Sum of Natural Numbers Between Range using For Loop


[youtube https://www.youtube.com/watch?v=TnGRAxjWpHg]

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


Source Code: C Program To Calculate Sum of Natural Numbers Between Range using For Loop

 
#include<stdio.h>

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

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

    if(min > max)
    {
        temp = min;
        min  = max;
        max  = temp;
    }

    printf("\nNatural Numbers from %d to %d are:\n", min, max);

    for(count = min; count <= max; count++)
    {
        printf("%d\n", count);
        sum = sum + count;
    }

    printf("Sum of Natural Numbers from %d to %d is %d\n", min, max, sum);

    return 0;
}

Output 1:
Enter 2 positive numbers
5
10

Natural Numbers from 5 to 10 are:
5
6
7
8
9
10
Sum of Natural Numbers from 5 to 10 is 45

Output 2:
Enter 2 positive numbers
14
10

Natural Numbers from 10 to 14 are:
10
11
12
13
14
Sum of Natural Numbers from 10 to 14 is 60

Logic To Calculate Sum of Natural Numbers Between Range using For Loop

We ask the user to enter minimum and maximum number(i.e., the range) and we store it inside variable min and max. If value of min is greater than value of max, then we swap the values of min and max.

We initialize the variable count to min and iterate through the for loop until count value is less than or equal to value of max. We keep incrementing the value of count by 1 for each iteration of for loop.

Inside for loop we add the value of count to previous value of sum and once the control exits the for loop we display the value present in variable sum.

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

Leave a Reply

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