# Can't seem to figure out the problem

This topic is 3373 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey, I was making this class for presenting fractions. To write a fraction in simple form, i formed this function called gcd, but I am getting a really weird result when I try the program. Here's my code. #include <iostream> using std::cout; using std::cin; int gcd(int n, int d) { cout << "\nn = " << n << " d = " << d; if (d % n == 0) { return n; } else { cout << "\nd % n = " << d % n; gcd((d % n), n);} } int main() { int x = 0; // first number int y = 0; // second number int hcf = 0; cout << "Enter 1st number : "; cin >> x; // store first number cout << "\nEnter 2nd number: "; cin >> y; // store second number hcf = gcd (x , y); // store gcd in hcf cout << "\n\nHCF of " << x << " & " << y << " = " << hcf; // print gcd } The weird thing is that the result is always 4...In function gcd, if I add a line "cout << n " before "return n", it gives the correct gcd, but the return value of the function is always 4. Any idea as to why this is happening? thanks a lot

##### Share on other sites
You've forgotten a return statement:

int gcd(int n, int d) {	cout << "\nn = " << n << " d = " << d;	if (d % n == 0) {		return n;	} else {		cout << "\nd % n = " << d % n;		return gcd((d % n), n);   // <<-- here	}}

If you're using Visual Studio, a C4715 warning should have been issued.

##### Share on other sites
Ohh, I see. Thanks a lot for the quick reply :)

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 11
• 15
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
634151
• Total Posts
3015825
×