When the if statement is deleted, the code runs without problems. What is the reason for that? This code gives the Greatest Common Divisor (GCD) of two numbers (m and n) the user should input.
#include <stdio.h>
int main() {
int m, n, r;
scanf("%d,%d", &m, &n);
if (m < n) {
r = m;
m = n;
n = r;
}
do {
r = m % n;
m = n;
n = r;
} while (r != 0);
printf("%d\n", m);
return 0;
}
CodePudding user response:
It is not important whether m
is greater than n
. If m
initially is less than n
then in the first iteration of the do-while loop
do {
r = m % n;
m = n;
n = r;
} while (r != 0);
m
will be greater than n
due to the statement
m = n;
For example let's assume that m
is equal to 2
and n
is equal to 10
. So r
equal to m % n
will be equal to 2
and in fact these statements
m = n;
n = r;
swap m
and n
in the first iteration of the loop.