Home > Blockchain >  Using two arrays as an if condition in a nested for loop
Using two arrays as an if condition in a nested for loop

Time:11-06

I'm relatively new to C/C , and I'm learning about nested for loops and arrays. The question I'm asking is referring to the code below

int main(){
    int N, M;
    bool secret = false;
    scanf("%d %d", &N, &M); //N is the amount of weapon "The Hero" has, while M is the amount for "The Villain"
    int X[N]; // To store the value of "Damage" each weapon has
    int Y[M]; 
    for(int i = 0; i < N; i  ){
        scanf("%d", &X[i]); // Inputting the value to each weapon
    }
    for(int i = 0; i < M; i  ){
        scanf("%d", &Y[i]);
    }
    for(int i = 0; i < N; i  ){
        for(int j = 0; j < M; j  ){
            if(X[i] > Y[j]){  //To check if atleast one weapon of "The Hero" can beat all the weapon of "The Villain" (What i was trying to do anyways)
                secret = true;
            } else{
                secret = false;
            }
        }
    }
    if(secret == true){
        printf("The dark secret was true\n");
    } else{
        printf("Secret debunked\n");
    }
    return 0;
}

I am trying to check if at least one weapon in the X array has a greater value than all of the ones is the Y array(not the sum of Y array). The problem I'm running into is that if I put a the last value in the X array as lower than any of the value in the Y array, it will always return false, and print out out the else statement, because the loop will always got to the last iteration and use that as the statement for the condition.

I was expecting the outcome to be

3 5 // The amount of weapons the Hero and Villain has
4 9 2 // The value of each weapon for the Hero
8 4 6 8 3 // The value of each weapon for the Villain

The dark secret was true // The expected output

instead, I got

Secret Debunked

because of the looping to last value in the X array. I tried to stop the if statements using break;, using it in the loop it self, both didn't work as expected. I'm thinking of arranging it first then using specific indexes to compare it. But before trying that I figured to ask here first.

CodePudding user response:

The problem is that you are always setting the variable secret in each iteration of the inner for loop. So the variable stores its last assigned value.

Rewrite the loops for example the following way

for ( int i = 0; !secret && i < N; i   ){
    int j = 0;

    while ( j < M && X[i] > Y[j] ) j  ;

    secret = j == M;
}

CodePudding user response:

breaking the loop once you have found a value (for hero) greater than that for villian will help

for (int i = 0; !secret && i < N; i  ) { // <= secret == true then exit
    for (int j = 0; j < M; j  ) {
        if (X[i] > Y[j]) {
            secret = true;
            break;  // <= found value, no need to check anymore
        } else{
            secret = false;
        }
    }
}
  • Related