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

by | Feb 1, 2023 | C, C Programs

Home » C » C Programs » C program to calculate the sum of natural numbers (Using for loop)

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

  • for loop in C
  • Go through the article on the ‘for’ 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
for(int i=1;i<=x;i++) // Initialization of ‘i’, Condition check for ‘i’, increment in ‘i’ is done
in single statement.


{
sum=sum+i; //every value of i will be added to sum
}
printf("Sum of all natural numbers upto %d is: %d",x,sum); //prints final value of 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.

for(int i=1; i<=x; i++) iterator ‘i’ initializes with value 1 and iterate upto ‘x’.

when i=1, and the value of sum is 0 thus the statement

sum=sum+i; results 0+1=1.

Now the value of the sum is 1.

‘i’ gets incremented, and the value of ‘i’ becomes 2.

Thus, sum=1(sum)+2(i)=3.

Thus, the updated value of the sum is 3.

This will go until ‘i’ becomes 254, and then the final value of the sum will become 32385.

 

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.

Author