Home > Enterprise >  My find-biggest-number Recursive function returns a discremented value
My find-biggest-number Recursive function returns a discremented value

Time:11-25

I have a problem in this recursive function that basically takes two numbers and returns the biggest one of them without using comparison (> || < ) operators, thing is, it returns dicremented values even though I held the starting values in a variable.

Here's my code:

#include <stdio.h>

int WhoBig(int A, int B) {
    int TrueA=A, TrueB=B;
    if(A==0)
    {
        return TrueB;
    }
    else if(B==0)
    {
        return TrueA;
    }
    else 
    {
        return WhoBig(A-1,B-1);
    } 
}

void main() {
    printf("%d",WhoBig(9,2));
    //Output:7 
}

CodePudding user response:

The type of the function parameters and of its return type should be an unsigned integer type. Otherwise the function can invoke undefined behavior if negative values will be passed to the function.

What you need is to add 1 to the returned value of each recursive call. Otherwise you are returning a decremented value.

The function can look the following way

unsigned int WhoBig( unsigned int x, unsigned int y ) 
{
    if ( x == 0 )
    {
        return y;
    }
    else if ( y == 0 )
    {
        return x;
    }
    else 
    {
        return 1   WhoBig( x - 1, y - 1 );
    } 
}

Here is your updated program.

#include <stdio.h>

unsigned int WhoBig( unsigned int x, unsigned int y )
{
    if (x == 0)
    {
        return y;
    }
    else if (y == 0)
    {
        return x;
    }
    else
    {
        return 1   WhoBig( x - 1, y - 1 );
    }
}

int main( void )
{
    printf( "%u\n", WhoBig( 9, 2 ) );
}

Its output is

9

Pay attention to that the function main without parameters shall be declared like

int main( void )

CodePudding user response:

you are not really saving the true value of A or B you are holding them in variables then you return the new value returned by WhoBig function i would go with something like this:

   #include <stdio.h>

int WhoBig(int A, int B) {
    int TrueA=A, TrueB=B;
    if(A==0)
    {
        return TrueB;
    }
    else if(B==0)
    {
        return TrueA;
    }
    else 
    {
        return 1   WhoBig(A-1,B-1);
    } 
}

void main() {
    printf("%d",WhoBig(9,2));
    
}
  • Related