C++ Program to Calculate Sum of Natural Numbers (Using for loop)

by | Jan 14, 2023 | C++, C++ Programs

Introduction

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

To understand this program, you must have gone through the following concepts of C++ programming

1. for loop

2. operators

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<iostream>
using namespace std;
int main()
{
int num;
// num is the value up to where the sum is calculated
cout<<"Enter a positive integer: ";
cin>>num;


int sum=0;
for(int i=1;i<=num;i++)
{
sum=sum+i;
}
cout<<"Sum: "<<sum;
return 0;
}

 

Output

Explanation

int num;

‘num’ is the variable declared to store the value up to where the user wishes to calculate the sum.

cout<<“Enter a positive integer: “;

cin>>num;

Using cout and cin statements, we take input from the user.

int sum=0;

A new variable is declared and initialized with a 0 value to store the sum of natural numbers.

for (int i=1;i<=num;i++)

for loop starts here with iterator ‘i’. ‘i’ iterates from 1 to ‘num’, and in each iteration, the value of ‘i’ is added to the sum.

sum=sum+i;

for i=1, sum=0

sum=sum+i=0+1=1

i++ updates the value of i to 2.

for i=2, sum=1

sum=1+2=3

i++ updates the value of i to 3.

for i=3, sum=3

sum=3+3=6

i++ updates the value of i to 4.

In this way, we get a final value containing the sum of natural numbers up to ‘num’

 

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.