Non-negative Product code doubt

Can anyone tell me why does this code fail test case 2 but if I store the input variable a to an array or vector and iterate that vector it works

#include <iostream>

using namespace std;

int main()
{
    int t;
    cin >> t;

    while (t--)
    {
        int n, result=1, a;

        cin >> n;

        for(int i=0; i< n; i++){
            cin >> a;
            
            if(a < 0){
                result *= -1;
            }else if(a == 0){
                result = 1;
                break;
            }
            
        }
        if(result < 0){
            cout << 1 << endl;
        }else{
            cout << 0 << endl;
        }
    }

    return 0;
}

Below code works but the above doesn’t

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int t;
    cin >> t;
    
    while (t--){
        
        int n, result = 1, a;
        cin >> n;
        std::vector<int> x;
        
        for(int i=0; i < n; i++){
            cin >> a;
            x.push_back(a);
        }
        for(auto z: x){
            if(z < 0){
                result *= -1;
            }else if(z == 0){
                result = 1;
                break;
            }
        }
        
        if(result < 0){
            cout << 1 << endl;
        }else{
            cout << 0 << endl;
        }
    }

    return 0;
}
1 Like
for(int i=0; i< n; i++){
    cin >> a;
            
    if(a < 0){
        result *= -1;
    }else if(a == 0){
        result = 1;
        break; <--- Error cause
    }
}

the moment you break out of the for-loop, you miss to read input. You continue the next test case and read input that should belong to an earlier test case.

1 Like

Oh thanks was stuck on this problem for some time