C program to calculate the sum of natural numbers (Using while loop)


This program is used to calculate the sum of first n natural numbers, where n is any value up to the user’s wish to calculate the sum.

To understand this program, you all should know about

  • while loop in C
  • Go through the article of ‘while’ loop written in the C language series to get a better understanding.
  • The positive numbers that start from 1 are known as Natural numbers.
  • The sum begins from 1 since natural numbers start from 1.



int main()


int x;

printf("Enter a positive integer:\n");


int sum=0; // 'sum' is declared and initialized with 0

int i=1; //Initialization

while(i<=x) //Condition



i++; // increment in i


printf("Sum of natural numbers upto %d is %d",x,sum);

return 0;





Variable ‘x’ will store the value up to which the user wants to calculate the sum.

int sum=0;

The variable ‘sum’ is declared and initialized with 0.

int i=1; ‘i’ iterator will be used in the while loop.


In the while loop, we have to write the condition and it will give true until ‘i’ becomes equal to ‘x’.

In each iteration, the body of the while loop is executed.

sum=sum+i; the value of sum is updated with the addition of I and then ‘i’ is incremented with the use of the statement written below.


The above code reflects the difference of the while loop from the for a loop. Initialization of ‘i’, Condition check for ‘i’, increment in ‘i’ is done in different statements in ‘while’ loop whereas in ‘for’ loop all the three steps were written in a single statement.




  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.