Search code examples
arrayscif-statementreturnfunction-definition

what is wrong with my if condition? it doesn't return the right value. in this case it should return 'F'. (Matching 1D Array)


The function should return 'T' if each element in the first array is equal to it corresponding element in the second array, and return 'F' if there is any difference between two array.

#include <stdio.h>

char match_array(int a[10], int b[10]);

int main()
{    
    int a1[10] = {1,2,3,4,5,6,7,8,9,10};
    int a2[10] = {0,0,0,4,5,6,7,8,9,10};
    char match;

    match = match_array(a1, a2);    
    printf("%c", match);
    
    return 0;
}

char match_array(int a[10], int b[10])
{
    int i;

    for(i=0; i<10; i++){
        if(a[i] == b[i]){
            return 'T';
        }
    }
    return 'F';
}

Solution

  • Check your code for match_array once again clearly.

    char match_array(int a[10], int b[10])
    {
        int i;
    
        for(i=0; i<10; i++){
            if(a[i] == b[i]){
                return 'T';
            }
        }
        return 'F';
    }
    

    Here whenever two corresponding elements of array are equal, you are returning T. Which means, return true when 'any' two corresponding elements are equal. I guess, this is not you intended. To return true when 'all' corresponding elements are equal, you should modify your code to this:

    char match_array(int a[10], int b[10])
    {
        int i;
    
        for(i=0; i<10; i++){
            if(a[i] != b[i]){
                return 'F';
            }
        }
        return 'T';
    }
    

    Here whenever, two corresponding elements are unequal, you would return false. You should return true only when you have iterated over entire array, and found that no elements are unequal.