Search code examples
c++recursionreturngarbage

C++, recursive correct answer but not being returned correctly


Ok, so heres my simple program for calculating Greatest common divisor. It is returning a garbage value everytime the same as 46332964. Ive thought over my head for an hour but cant seem to understand the problem. After research, i also included the prototype but still no luck. It works until it returns. Please copy the code and run it and please help me.

#include <iostream>
using namespace std;

int calculate_gcd(int aa, int bb, int rem, int g);

int main()
{
    int a, b;
    int rem = -1;
    int gcd=0;

    cout << "Number 1: "; //taking inputs
    cin >> a;
    cout << "Number 2: ";
    cin >> b;

    if (a < b) //swapping if number greater than the number according to the code
    {
       a = a + b;
       b = a - b;
       a = a - b;
    }

    gcd = calculate_gcd(a, b, rem, gcd);

    if (a <= 0 || b <= 0)
    {
       rem = 0;
       cout <<"GCD doesnot exists\n";
    } //just in case of zeros
    else
        cout << "\nthe GCD of "<<a <<" and "<<b <<" is "<<gcd <<"\n\n"; //the main answer

    system("pause");
    return 0;
}

int calculate_gcd(int aa, int bb, int rem, int g)
{
    if (rem != 0)
    {
       if (aa%bb == 0)
        {
           rem = 0;
           g = bb;
           printf("**GCD is %d\n", g);
        }
        else {
             rem = aa % bb;
             aa = bb;
             bb = rem;
        }
        calculate_gcd(aa, bb, rem, g);
    }
    else {
         printf("**here also GCD is correct as %d \n", g);
         return g; //returning 
         }
}

Solution

  • You're missing a return. You should use return calculate_gcd(aa, bb, rem, g); instead of just recursing.

    You can catch this with clang using -Wreturn-type. Other compilers probably also have a warning for this.