user4460784
user4460784

Reputation:

Function in C not returning proper value

I'm trying to check whether an array is sorted without using a loop. It's working properly, i,e. if I have an array with elements that are in ascending order, the printf executes, since I get "Sorted." But

printf("Array 1 returns: %d \n\n", sortCheck(arr1, SORTED1));

returns 0? Why is this?

Thanks. Here's the entire code.

#include<stdio.h>

const int SORTED1 = 5;

int sortCheck (int arr[], int arrSize);

int indexCounter = 0;

int main()
{
    int arr1[] = {1,2,3,4,5};

    printf("Array 1: \n");
    printf("Array 1 returns: %d \n\n", sortCheck(arr1, SORTED1)); 


    indexCounter = 0; 
    return 0;
}

int sortCheck(int arr[], int arrSize)
{   
    if ( (arr[indexCounter]==arr[arrSize-1]) && (indexCounter==arrSize-1) )
    {
        printf("Sorted. \n");
        return 1;
    }
    if ( arr[indexCounter] <= arr[indexCounter+1] )
    {
        indexCounter++;
        sortCheck(arr, arrSize);
    }
    else
    {
        printf("Not sorted.");
        return 0;
    }   
}

Upvotes: 1

Views: 142

Answers (3)

user3629249
user3629249

Reputation: 16540

the sortCheck() function does not check if the array is sorted.

there are two reasons for this.

1) when the recursive call was invoked, the returned value is being ignored, so the information about a particular byte pair is lost.

2) the index (arrSize) is always passed, rather than the offset to the current byte index

I.E. the whole sortCheck() function needs to be re-designed.

Using a debugger (or a printf( of the parameters) in the path that calls the recursive sortCheck() would have revealed that fact.

Upvotes: 0

Ravi
Ravi

Reputation: 11

Following changes should print value 1

int sortCheck(int arr[], int arrSize)
{   
    int val = 0;
    if ( (arr[indexCounter]==arr[arrSize-1]) && (indexCounter==arrSize-1) )
    {
        printf("Sorted. \n");
        return 1;
    }
    if ( arr[indexCounter] <= arr[indexCounter+1] )
    {
        indexCounter++;
        val = sortCheck(arr, arrSize);
        return val;
    }
    else
    {
        printf("Not sorted.");
        return 0;
    }   
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206717

You are seeing undefined behavior due to a missing return statement.

if ( arr[indexCounter] <= arr[indexCounter+1] )
{
    indexCounter++;

    // Problem. Missing return.
    sortCheck(arr, arrSize);
}

Change the offending line to:

    return sortCheck(arr, arrSize);

Upvotes: 5

Related Questions