Hey guys! I have an exam tomorrow and just want some one to take a quick look over this program(GCD program) . I added comments for quick understanding.Thanks in advance for letting me know if it works or not.
#include <iostream>
usingnamespace std;
//prototype for gcd funtion
int gcd(int,int);
int main()
{
//variables that store user input values
int num1,num2;
//display messages
cout << "\t\t\tWelcome to finding GCD!!\n\n";
cout << "Enter first number ";
cin >> num1; //extracting input value from user
cout << "Enter second number ";
cin >> num2;
//display result and calling gcd funtion
cout << "The GCD of both numbers are" << gcd(num1,num2) << endl;
return 0;
}
//gcd funtion
int gcd(int x, int y)
{
//variable to store gcd
int value;
//conditional operator to check for gcd
(x%y==0)?value=y:value=x;
//return gcd
return value;
}
Haven't you tried to compile it?
And, no, it won't work.
Firstly, you conditional operator doesn't work like that. The proper syntax would be value = x%y==0 ? y : x;,though you don't need this at all... What you are saying now is that if x is divisible by y, then the gdc(x, y) is equal to y (which is true) and to x otherwise (which makes no sense).
Here's a suggestion make a for loop that goes from x to 2. Let's call the loop variable i. When x%i == 0 and y%i == 0, i is the gcd.
Good luck