To get the sum of n numbers, there can be two cases:
- Add consecutive n numbers.
- Add any n numbers.
Method 1 – Sum of n consecutive numbers without an array(using while loop)
Algorithm:
- Take input of n till which we need to get the sum.
- Initialize a variable sum and declare it equal to 0(to remove garbage values).
- Using while loop, add all numbers 1 to n.
- 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
Report Error/ Suggestion