Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"If statement" deleted, c code runs without problem, what is the reason?

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading