GCD problem

I really don't need help with the gcd formula. I have that down, but I keep getting strange errors that I don't know how to fix. Here is my code.

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
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;

int greatestCommonDivisor( int a, int b )
{
	int c;
	a = abs(a);
	b = abs(b);

	if (b = 0)
		return a;
	else
		while (b > 0)
		{
			c = b;
			b = a % b;
			a = c;
		}
		return c;
}

int main ()
{
	int x;
	int y;
	int gcd;

	cout << "Please enter the first number" << endl;
	cin >> x;
	cout << "Please enter the second number" << endl;
	cin >> y;

	while ( x < y );
	do
	{
		cout << "Invalid entry, x is smaller than y. Please enter first number." << endl;
		cin >> x;
		cout << "Please enter a number smaller than the first number for the second number." << endl;
		cin >> y;
	}

	gcd = greatestCommonDivisor( x, y );

	cout << "The greatest common divisor is" << gcd << endl;

	getchar();

	return 0;
};


At line 44 I am getting this error "syntax error: identifier 'gcd'"
Also, I am getting an error saying I am trying to use "int c" without initializing it. I can't figure out what went wrong!
Also, I am getting an error saying I am trying to use "int c" without initializing it.


Exactly what it says on the tin. You are using "c" without assigning a value to it first.

The syntax error is because you do this
1
2
3
4
5
6
7
8
9
while ( x < y );
	do
	{
		cout << "Invalid entry, x is smaller than y. Please enter first number." << endl;
		cin >> x;
		cout << "Please enter a number smaller than the first number for the second number." << endl;
		cin >> y;
	}


When it should be this:

1
2
3
4
5
6
7
while ( x < y )
	{
		cout << "Invalid entry, x is smaller than y. Please enter first number." << endl;
		cin >> x;
		cout << "Please enter a number smaller than the first number for the second number." << endl;
		cin >> y;
	}


The syntax error occurs at gcd because "while" is expected there (for a do-while loop).

Also please look at the first if in your gcd function. I don't think you want it to do what it does.
Last edited on
Ok I fixed the two errors, but I don't really know what you mean about the if. Also my output stops after I enter the value for y and I cant determine why...
1
2
3
4
5
6
7
8
9
10
11
12
if (b = 0) //b is set to 0. This is never true because the value of this expression is 0. == is check for equality.
		return a;
	else
		while (b > 0) //since b is always 0 here, the loop is never entered
		{
			c = b;
			b = a % b;
			a = c;
		}
		return c; /*unitialized value for c is returned.
                                Or maybe initialized if you assigned a value to c now. 
                                Anyways it's not what you want*/
Last edited on
Ah! Thank you! I totally forgot about the whole = and == thing. I feel so silly...
Topic archived. No new replies allowed.