Home > Blockchain >  What is the value given to 'mcm'?
What is the value given to 'mcm'?

Time:01-04

That's the solution to the "Write a program that calculates the minimum common multiple of two numbers in C" our proffesor posted.

#include <stdio.h>
#include <conio.h>

int main() {
    int n1, n2, mcm;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    mcm = (n1 > n2) ? n1 : n2;

    while (1) {
        if (mcm % n1 == 0 && mcm % n2 == 0) {
            printf("The Minimum Common Multiple of %d and %d is %d.", n1, n2, mcm);
            break;
        }
          mcm;
    }
    return 0;
}

This is the same code you can find on programiz but without including the conio.h library. What is the purpose of using the whole line where mcm gets a value? Does it have something to do with the conio.h library? When i wrote the code myself i just stated mcm=1; and it worked just fine.

CodePudding user response:

It saves some cpu cycles, since you know values less than the larger of the two inputs cannot be a common multiple of the two values, so there is no need to test those values.

CodePudding user response:

This is the Ternary Operator. To quote:

<condition> ? <true-case-code> : <false-case-code>;

The ternary operator allows you to execute different code depending on the value of a condition, and the result of the expression is the result of the executed code.


What is the purpose of using the whole line where mcm gets a value?

So your line of code:

mcm = (n1 > n2) ? n1 : n2;

It means:

if (n1 > n2)
    mcm = n1;
else
    mcm = n2;
  •  Tags:  
  • Related