redapple
redapple

Reputation: 21

Why does it return 1?

Goal of program: return 1 if two arrays are identical. if not return 0. What I did:

#include <stdio.h>


int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}


int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

It always returns 1 and I cannot find the reason why. What's wrong?

Upvotes: 2

Views: 108

Answers (3)

Arundeep Chohan
Arundeep Chohan

Reputation: 9969

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
     if (arr1[i] != arr2[i]) {
        return 0;
     }
   }
   return 1;
}

This only checks if 2 arrays have 3(len=3) similar values in a row.

Upvotes: 2

Sumit
Sumit

Reputation: 1115

You have just messed up the if-else statements, as in the first iteration you are checking and also terminating the loop by using the return statement, so it never goes on the next index.

Just replace the else return statement with continue and at the end of the function add a return statement as, return 1

    int identical ( int arr1[], int arr2[], unsigned int len ){
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            continue;
        }
    }

    return 1;

}

OR

You need to rewrite function declaration as follows (in efficent way):

int identical ( int arr1[], int arr2[], unsigned int len ){

   if (len == 0)    return 1;

    for (int i = 0; i < len; i++)
        if (arr1[i] != arr2[i])     return 0; 

   return 1;
} 

Thanks.

Upvotes: 1

learner
learner

Reputation: 3472

#include <stdio.h>


int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            if (i == len - 1){
              return 1;      
            }
        }
    }

}


int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

The problem with your code is that, you're returning from the function before the loop gets to complete its iterations.

Upvotes: 0

Related Questions