Home C Programming Language / 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,368 Views
💻 Practical Program
📘 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;
}
                        

🖥 Program 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
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.