C++ program to find sum of n numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C++ program to find sum of n numbers

find

26th Oct 2016, 12:15 PM
Nasireen Kv
Nasireen Kv - avatar
3 Answers
+ 12
#include <iostream> using namespace std; int main() { int sum=0, num; while(cin>>num){ sum+=num; } cout<< sum; return 0; }
26th Oct 2016, 12:22 PM
Lara
Lara - avatar
+ 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; }
26th Oct 2016, 12:26 PM
Remmae
Remmae - avatar
+ 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.
26th Oct 2016, 1:30 PM
Zen
Zen - avatar