C++ Recursive Functions

  • From: Jared Wright <wright.jaredm@xxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Tue, 13 Nov 2007 23:27:20 -0500

Hi there everyone, Well, I've hit a snag on an assignment for my C++ course. We are to use recursion to find the GCD (greatest common divisor) of two integers. The program will eventually progress to generating random numbers and using alternate algorithms (with counters to see which require more recursive function calls) but that's neither here nor there for the moment.


Within the main function, a call is made to the GCD function, giving it two integer parameters to work with (call them q and r). If r = 0, the function returns q. If not, the function calls itself again using the parameters r and q%r. Eventually the second integer should be 0, and the first integer should be the GCD I'm looking for. If I manually input 0 as the second integer in the initial function call, everything works fine. But if recursion has to be utilized, I always get a return value of 136136, regardless of what the input values are. I think I might be pointing somewhere incorrectly, but I can't spot it and don't have the knowledge to say for sure that's even the problem. Any guidance is appreciated. The relevant code is below for your perusal. Thanks in advance.

JW


#include <iostream>
using namespace std;
int gcd(int, int); // Declare GCD function.

int main ()
{
int q(0), r(0), temp(0); // Declare main function's variables and create temp variable. cout << "Please enter two numbers whose GCD is to be found.\nPress enter after inputting the first number,

then enter the second and press enter again.\n";
   cin >> q >> r;
   if (r > q) {
       temp = q;
       q = r;
r = temp; // This is for an instance where the first number is smaller than the second.
   }
cout << "The greatest common divisor of " << q << " and " << r << " is " << gcd(q, r) << ".\n"; // Here is the function call that keeps returning 136136.
   return 0;
}
int gcd(int q, int r) // GCD function definition begins here.
   {
   if (r == 0)
       return q;
   else
gcd(r, q%r); // And this is where the recursion is, and I think the trouble is somewhere around here.
   }
__________
View the list's information and change your settings at //www.freelists.org/list/programmingblind

Other related posts: