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

by | Jan 19, 2023 | C, C Programs

Introduction

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.

Program

#include<stdio.h>
int main()
{
int x;
printf("Enter a positive integer:\n");
scanf("%d",&x);
int sum=0; // 'sum' is declared and initialized with 0
int i=1; //Initialization


while(i<=x) //Condition
{
sum=sum+i;
i++; // increment in i
}
printf("Sum of natural numbers upto %d is %d",x,sum);
return 0;


}

 

Output

Explanation

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.

while(i<=x)

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.

i++;

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.

 

 

0 Comments

Submit a Comment

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.