Home / Programs / Program to calculate the sum of first n natural numbers using while loop
Programming Example

Program to calculate the sum of first n natural numbers using while loop

👁 2,367 Views
💻 Practical Program
📘 Step by Step Learning
Program to calculate the sum of first n natural numbers using while loop

Program Code

// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
    int num, count, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &num);
    
      count = 1; 
     
    while(count <= num)
    {
        sum += count;
        ++count;
    }

    printf("Sum = %d \n", sum);

    return 0;
}

Output

Enter a positive integer: 10
Sum = 55
Press any key to continue . . .

Explanation

Program to calculate the sum of first n natural numbers using while loop

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.