My instructions were to: Write a function int gcd( int a, int b); which returns the value of the greatest common divisor of the two integers a and b . You can do this either recursively or iteratively. Incorporate this function into a program that uses a testing loop. Each iteration in the loop reads two integers and then prints the value of their greatest common divisor. Note: In the case that a = b = 0, there is no greatest common divisor (since every positive integer divides 0, and there is no largest positive integer.) In such a case, you should not call the gcd function, but print "There is no gcd."
However, there a few errors in my code that I'm not sure how to fix.
I know that on lines 25, and 36 I get an "A function-definition is not allowed here before" error. There are probably a few others. Please help me fix them! Thank you so much!!
#include <iostream>
usingnamespace std;
int main() {
char c;
// declaration of needed variables
while ( 1 ) {
cout << "Press q to quit or anything else to continue ";
cin >> c;
cin.ignore( 256, '\n' );
if ( c == 'q' or c == 'Q' ) {
cout << "\n\nUser quits the program.\n\n";
break;
}
// testing code start here
int gcd (int, int);
int main () {
int a, b;
cout << "Enter an integer for a: ";
cin >> a;
cout << "Enter an integer for b: ";
cout>> b;
cout << "The GCD of the two integers is :" << gcd(a,b) << endl;
return 0;
}
int gcd (int a, int b)
{
if (a==b)
return a;
while (b!=0 | | a!=0)
{
if (b !=0)
{
a %= b;
}
elsereturn a;
if (a != 0)
{
b %= a;
}
elsereturn b;
cout << "There is no gcd." ;
}
}
// testing code ends here
cout << "\n--------------------------\n\n";
}
return 0;
}
In that case, you should re-read over the introductory sections about how to structure a program because you have some serious syntactical errors. If, after doing that, you still aren't sure what's wrong, post again with any ideas you have about the problem.