Home > OS >  C : How to find the sum of a series of numbers separated by spaces
C : How to find the sum of a series of numbers separated by spaces

Time:11-09

I am trying to create a programme taking two lines of imput, say

n
m1, m2, m3, ... , mn

where 1, 2, 3 ... n are all subscipts, so that n is the total number of integers that will be entered, and m1...mn are the integers themselves. Now, I want to find a way to sum m1 to mn up.

For example, if the user entered 5 as the first input line, we know that the user will input 5 numbers separated by space, but in the same line, say 12 14 17 19 28, the expected output should be 90. I understand that to take in inputs we need to use cin >> a >> b >> c >> d >> e after all the five variables have been defined. However, I am unable to find a way to solve it as the input on the first line is not always 5, and if it's 1000, it is not realistic to write cin >> a >>b ... 1000 times. Anyone can help? Thanks!

CodePudding user response:

You said in comments:

If different lines I can still use for loop cin. But single line when the quantity is not confirmed is hard :(

You can use a for loop regardless of whether the numbers are on a single line or on different lines. operator>> skips leading whitespace, and then stops reading on whitespace. Space and NewLine characters both count as whitespace. So, the following will work just fine (error handling omitted for brevity):

int n, num, sum = 0;
cin >> n;
for (int i = 0; i < n;   i) {
    cin >> num;
    sum  = num;
}

CodePudding user response:

#include <bits/stdc  .h> 
using namespace std;
int main() {
    int n;
    cin >> n;
    int sum = 0, value = 0;
    while (cin>>value){
        sum =value;
    }
    cout << sum;

    return 0;
}

I have a working answer here (definitely not the best) but the n here is useless (the one telling you how many numbers to sum up)

  • Related