C Program To Calculate the Sum of Natural Numbers From 1 to N using For Loop

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

Related Read:
For Loop In C Programming Language
C Program to Print Natural Numbers from 1 to N using for loop

Video Tutorial: C Program to Calculate the Sum of Natural Numbers From 1 to N using For Loop


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

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


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

 
#include<stdio.h>

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

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

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

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

    printf("\nSum of natural numbers from 1 to %d is: %d\n", num, sum);

    return 0;
}

Output 1:
Enter a positive number
5

Natural Numbers from 1 to 5 are:
1
2
3
4
5

Sum of natural numbers from 1 to 5 is: 15

Output 2:
Enter a positive number
10

Natural Numbers from 1 to 10 are:
1
2
3
4
5
6
7
8
9
10

Sum of natural numbers from 1 to 10 is: 55

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.

For Loop
Variable count is assigned value 1. For loop executes until count value is less than or equal to the user entered number. For each iteration of for loop, count value increments by 1.

Inside for loop, we display the value of count(which is natural number between 1 and user entered number). We also keep adding the value of count to the previous value of variable sum. Once the control exits for loop, sum will have the sum of all the natural numbers between 1 to user entered number.

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