c++ sums

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main(){
	int sum = 0;
	int line;
	cin >> line;
	for (int i = 0; i < line; i++){
		int x, y;
		cin >> x >> y;
		sum = x + y;
	}
	cout << sum;
}


If I enter:
3
5 2
6 8
7 4

It just outputs: 11
But it should output: 7 14 11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main(){
    int sum = 0;
    int line;
    cin >> line;
    for (int i = 0; i < line; i++){
        int x, y;
        cin >> x >> y;
        sum = x + y;
        cout << sum; //←-\
    }           //       |
//  cout << sum; --------/
}
Last edited on
Hope this helps.

The cout << sum; needs to be inside the loop for it to display each answer every time. Can I ask why you are using the int line?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int sum;
int line;

int main()
{
	cin >> line;
	for (int i = 0; i < line; i++)
	{
		int x, y;
		cin >> x >> y;
		sum = x + y;
		cout << "= " << sum << "\n______\n";
	}

}
Topic archived. No new replies allowed.