# Program to find sum of n natural numbers in C++ [3 Methods]

Written by

One of the fundamental programs used to understand iterative statements, a program to find the sum of n natural numbers has plenty of applications.

Before beginning, let us recap the 3 loops used for iterations in C++ that allow a set of instructions to be repeated until a certain condition is met.

- i)
**The for loop:**The simplest of them all, the for loop has a clear and concise structure with all the top control statements in one place. This loop is particularly used when one knows the number of times a set of statements need to be repeated. Eg: To print the multiplication table of 5. - ii)
**The while loop:**The most commonly used loop, this one executes the looping statements until the specified condition is met, while can be used in just any situation. However, it is best used when one does not know the number of times a piece of code needs to run and break the loop with a given condition. Eg: Any program with decrements like factorial calculation. - iii)
**The do-while loop:**Unlike the for and while loops mentioned above, do-while is an exit-controlled loop, which implies that the condition is checked in the end. Hence, this loop executes its enclosed piece of code at least once, making it suitable for displaying menu pages. Use this loop when you want to execute the looping statements at least once no matter what the initial state of the text expression or condition is.

Using the above loops, we proceed to our code to calculate the sum of n natural numbers.

This problem statement gives rise to 2 possible cases:

- Adding consecutive numbers, i.e, 1 to ‘n’.
- Adding any ‘n’ numbers.

**Approach 1 – Consecutive Numbers**

To begin with, let us look at a program to print 1 to n numbers.

```
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,sum=0;
cout<<"Enter the value of n: "; cin>>n;
int i=n; //Variable to store value for output
while(n>0)
{
sum+=n;
n--;
}
cout<<"\n The sum of first "<<i<<" natural numbers is: "<<sum;
return 0;
}
```

```
Enter the value of n: 4
The sum of first 4 natural numbers is: 10
```

The same program can be written with for and do-while loops:

**for loop:**

```
for(int i=1;i<=n;i++){
sum+=i;
}
```

**do while loop:**

```
do{
sum += n;
n--;
}while(n > 0);
```

**Approach 2** – Specified n numbers

**Approach 2**– Specified n numbers

In this method, the user inputs n numbers of their choice to generate the sum. This program resembles the usual addition that one does with a calculator.

Generating the sum of n different numbers can again be carried out in two ways:

- Without Arrays
- With Arrays

**Without Arrays**

The code without arrays is fairly simple.

**Algorithm:**

Step 1: Enter the number of values the user would like to enter (n)

Step 2: Initialize a variable ‘sum’ and assign 0 to it so as to avoid garbage values.

Step 3: Run a loop to accept n values through a variable and add it to the ‘sum’ variable.

Step 4: Print the ‘sum’ variable.

**Code:**

```
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,sum=0,number;
cout<<"Enter the value of n: "; cin>>n;
cout<<"\n Enter the numbers:";
int i=1;
while(i <=n ){
cout<<"\n Enter number "<<i<<": "; cin>>number;
sum += number;
i++;
}
cout<<"\n The sum is:"<<sum;
return 0;
}
```

**Output**

`Enter the value of n: 4 Enter the numbers:`

Enter number 1: 2

Enter number 2: 5

Enter number 3: 3

Enter number 4: 3

The sum is: 13

The above code can be modified to feature a for or do while loop instead of the while loop, in this way:

**For loop**

`for(int i=1;i<=n;i++){ cout<<"\n Enter number "<<i<<": "; cin>>number; sum+=number;`

`}`

**do while loop**

```
int i=1;
do{
cout<<"\n Enter number "<<i<<": "; cin>>number;
sum+=number;
i++;
}while(i <= n);
```

**With Arrays**

Arrays are a group of similar data types stored in contiguous memory locations. Once stored, the array can be used in several ways to extract data for various applications, and in this case, the task is to find the sum of the given input.

Let’s define a practical example to understand the nitty gritties of the above agenda. Say we want to calculate the total marks scored by a class of 10 students and calculate the class average.

Instead of declaring 10 different variables or simply looping them, we can use an array to pass the marks of the students and then calculate the sum and average of the class.

**Algorithm:**

Step 1: Initialize an array of size n and a variable ‘sum’

Step 2: Enter the number of values the user would like to enter (n)

Step 3: Run a for loop to initialize the elements of the array and also update the value of ‘sum’ with every iteration.

Step 4: Print the sum.

Using the above algorithm, we will now calculate the total and average marks obtained for an array of students.

**Code:**

`#include<bits/stdc++.h> using namespace std; int main(){ int n; cout<<"Enter Class strength "; cin>>n; double arr[n], sum=0, avg; // Declaring as ‘double’ to avoid segmentation error cout<<"\n Enter Class Marks:";`

`for(int i=0;i<n;i++){ cout<<"\n Enter marks of student "<<i+1<<": "; cin>>arr[i]; sum+=arr[i]; } avg=sum/n; cout<<"\n The total marks obtained by the class is: "<<sum; cout<<"\n Class average: "<<avg; return 0;`

`}`

**Output**

`Enter Class strength 10`

Enter Class Marks: Enter marks of student 1: 78 Enter marks of student 2: 99 Enter marks of student 3: 87 Enter marks of student 4: 65 Enter marks of student 5: 55 Enter marks of student 6: 78 Enter marks of student 7: 93 Enter marks of student 8: 22 Enter marks of student 9: 40 Enter marks of student 10: 75

`The total marks obtained by the class is: 692 Class average: 69.2`