quick check please!did it all myself

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace 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;
	}
	
	
	
for letting me know if it works or not
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
I would suggest looking up GCD on Wikipedia. It gives a simple algorithm for GCD.
Topic archived. No new replies allowed.