RUN

# C++ Program for sum of n numbers

Written By -

To get the sum of n numbers, there can be two cases:

### Method 1 – Sum of n consecutive numbers without an array(using while loop)

Algorithm:

1. Take input of till which we need to get the sum.
2. Initialize a variable sum and declare it equal to 0(to remove garbage values).
3. Using while loop, add all numbers 1 to n.
4. Now, Print the sum.

Code:

``````#include<iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"Enter number till which you would like to add";
cin>>n;
while(n>0)
{
sum+=n;
n--;
}
cout<<"\n sum is:"<<sum;
return 0;
}``````

Output:

``````Enter number till which you would like to add: 3

sum is:6``````

### Method 2 – Sum of n numbers without an array(using while loop)

Code:

``````#include<iostream>
using namespace std;
int main()
{
int n,sum=0,number;
cout<<"How many numbers do you want to add?";
cin>>n;
cout<<"\n Enter numbers:";
while(n>0)
{
cin>>number;
sum+=number;
n--;
}
cout<<"\n sum is:"<<sum;
return 0;
}``````

Output:

``````How many numbers do you want to add? 7

Enter numbers:
1
2
3
4
5
89
34

Sum is:138``````

### Method 3: Sum of n numbers in array(using for loop)

Code:

``````#include<iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"How many numbers do you want to add?";
cin>>n;
int arr[n];
cout<<"\n Enter numbers:";

for(int i=0;i<n;i++)
cin>>arr[i];

for(int i=0;i<n;i++)
sum+=arr[i];

cout<<"\n sum is:"<<sum;
return 0;
}``````

Output:

``````How many numbers do you want to add? : 3

Enter numbers:
23
12
54

Sum is:89``````