+ 1
C++ program to find sum of n numbers
find
3 Answers
+ 12
#include <iostream>
using namespace std;
int main() {
int sum=0, num;
while(cin>>num){
sum+=num;
}
cout<< sum;
return 0;
}
+ 9
Or you can do it recursively
#include<iostream>
using namespace std;
int add(int n);
int main()
{ int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Sum = " << add(n);
return 0;
}
int add(int n)
{ if(n != 0)
return n + add(n - 1);
return 0; }
+ 4
If you want the sum of the first n numbers, it is equal to n*(n+1)/2.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << "Sum: " << n*(n+1)/2 << endl;
return 0;
}
However, if the aim was to learn to use loops or recursion, see the other answers.