Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My find-biggest-number Recursive function returns a discremented value

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 
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading