Try to search your question here, if you can't find : Ask Any Question Now ?

# How to make a function (no recursion allowed) that outputs the GCD of two inputted numbers?

HomeCategory: stackoverflowHow to make a function (no recursion allowed) that outputs the GCD of two inputted numbers?

I am trying to solve this challenge problem, where I am meant to find the GCD of two inputted numbers by referencing a function. However, I am not sure exactly where I am messing up. Here is the exact question for reference:

Ask the user for two integers, x and y from the console.
Write a function which accepts x and y as input parameters and calculates and returns the greatest common denominator of both values.
Output the returned value of the GCD function.

I tried making a function to find the GCD, and then just referencing the function later. I’m not sure what I’m doing wrong.

``````#include <iomanip>
using namespace std;

int gcdfunction(int n, int m);

int main(){
int i, n, m;
int gcd;

cout << "Enter an integer: ";
cin >> n >> m;

int variable = gcdfunction(n, m);

return 0;
}

int gcdfunction(int n, int m){

for (int i=1; i<=n; ++i){
int gcd = i;
if(n%i==0 && m%i==0) {
break;
}

return gcd;
}
}
``````

I should be getting this:
Enter two integers: 12 8
The GCD of 12 and 8 is 4.

But instead, I’m getting an error with gcd not being declared in this scope, which doesn’t make sense because I declared it as an int both inside the function and outside.

1 Answers
Your Answer

11 + 2 =

WP Facebook Auto Publish Powered By : XYZScripts.com