0

I have ruby version of this program & trying to do the same in C++

The input must be:

2 # Number of pairs 
562 -881 # First pair
310 -385 # Second pair

And output:

-319
-75

It's working fine with one array of 2 numbers and breaks if pairs > 2. What's wrong in my for loops?

#include <iostream>

using namespace std;

int main() {
    int sum = 0;
    int iter;

    cin >> iter;
    int arr[2];

    for (int i=0; i<iter; i++) {
        for (int n=0; n<2; n++) {
            // Enter numbers
            cin >> arr[n];
        }
    }

    for (int num=0; num<2; num++) {
        sum+=arr[num];
    }

    for (int i=0; i<iter; i++) {
        // Get the sum of numbers
        cout << sum << endl;
    }
    return 0;
}

Thanks for any help!

2
  • 1
    In your first loop, you overwrite the contents of arr each time. Commented Sep 23, 2015 at 8:19
  • And how it can be fixed? Commented Sep 23, 2015 at 8:27

2 Answers 2

1
for (int i=0; i<iter; i++) {
    for (int n=0; n<2; n++) {
        // Enter numbers
        cin >> arr[n];
    }
}

In first iteration values are entered in arr and again in second iteration previous values are overwritten (similar in next iterations if any ). This is the problem .

Solution -

#include <iostream>
using namespace std;

int main() {
    int iter;
    cin >> iter;
    int arr[2];
    int sum[iter];             // declare sum as array with iter number of elements
   for(int i=0;i<iter;i++){
        sum[i]=0;                 // initialize elements of sum to 0
     }
   for (int i=0; i<iter; i++) {
       for (int n=0; n<2; n++) {
        // Enter numbers
           cin >> arr[n];               // take iput 
           sum[i]+=arr[n];              // add numbers and store in sum
        }
    }


   for (int i=0; i<iter; i++) {
      // Get the sum of numbers
       cout << sum[i] << endl;          // print values in sum after taing all inputs 
    }
  return 0;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for watching this, but how exactly I can fix it?
@kirbrown I have added the solution . Please take a look. Click on link to see working demo.
1

You're overwriting the contents of arr on each iteration of the loop. Try something like this (live demo here):

#include <iostream>

using namespace std;

int main() {
    int sum = 0;
    int iter;

    cin >> iter;
    int arr[2];

    for (int i=0; i<iter; i++) {
        for (int n=0; n<2; n++) {
            // Enter numbers
            cin >> arr[n];
        }
        for (int num=0; num<2; num++) {
            sum+=arr[num];
        }

        cout << sum << endl;

    }

    return 0;
}

1 Comment

Thanks, but in this variant the output displays every time after each pair and breaks on 2nd, check this: 2 -> 20 10 -> 30 (ok) -> 30 40 -> 100

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.