k1r8r0wn
k1r8r0wn

Reputation: 800

For loop don't work properly for more than one array in C++

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!

Upvotes: 0

Views: 60

Answers (2)

ameyCU
ameyCU

Reputation: 16607

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;
 }

Upvotes: 1

anorm
anorm

Reputation: 2263

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;
}

Upvotes: 1

Related Questions