I'm new at programming, I was asked to create a program to find the GCD (Greatest common divisor) of two numbers my friend helped me create this program.
All i am asking is how does it function?, I know how the whole program works (If... If else, While, Looping, Modulo etc.) and how to find the GCD.
But i dont know how my program does it.

``````#include <iostream.h>
#include <conio.h>
int gcd(int a, int b);
int a, b;
int main()
{
clrscr();
cout<<"Enter the A Integer: ";
cin>>a;
cout<<"Enter the B Integer: ";
cin>>b;
gcd(a, b);
getch();
return 0;
}

int gcd(int a, int b)
{
int r;
if (a>b)
{
while (b!=0)
{
r=a%b;
a=b;
b=r;
}
cout<<"Greatest Common Divisor is: "<<a;
}
else if (b>a)
{
while (a!=0)
{
r=b%a;
b=a;
a=r;
}
cout<<"Greatest Common Divisor is: "<<b;
}
else
{
clrscr();
cout<<"Error!";
}
getch();
return 0;
}``````
2
Contributors
1
2
Views
6 Years
Discussion Span
Last Post by Schol-R-LEA

Let's start by separating the algorithm from the (extraneous) output:

``````#include <iostream>

int gcd(int a, int b);

int main()
{
int a, b;

std::cout<<"Enter the A Integer: ";
std::cin>>a;
std::cout<<"Enter the B Integer: ";
std::cin>>b;

std::cout << "The Greatest Common Divisor of " << a
<< " and " << b
<< " is " << gcd(a, b);
return 0;
}

int gcd(int a, int b)
{
int r;

// if a is greater than b, swap a and b
if (a < b)
{
r = a;
a = b;
b = r;
}

// now perform the algorithm
while (b != 0)
{
r = a % b;
a = b;
b = r;
}

return a;
}``````

I don't know if this helps or not, but it should make the algorithm itself show clearly. In general, you don't want to have the user input and output tnagled up in with the part of the code that performs the actual operations, if you can avoid it, as it makes it harder to understand.

There are two other points I'd like to make. First, you should indent you code to make it more readable, much like I have here. Second, the code you posted is for an older compiler, probably the ancient Turbo C++; if you have any choice in the matter, you should upgrade to a more modern compiler and IDE such as Code::Blocks or Visual C++ Express.

Edited by Schol-R-LEA: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.