Chapter 4 challenge solution? (Something is wrong here)


#1

Hello!

In the end of chapter 4, as you may know, the question is:

What will be printed to the console?

#include <stdio.h>

int main(int argc, const char *argv []) {

int i = 20;
int j = 25;

int k = ( i > j)? 10:5;

if ( 5 < j - k) {
printf(“The first expression is true.”);
} else if ( j > i) {
printf(“The second expression is true.”);
} else {
printf(“Neither expression is true.”);
}

return 0;
}

The result is: The first expression is true.

What I dont get is that the second expression is true also.
So why does only expression 1 shown as true?

It should be like this: Expression 1 is true. Expression 2 is true.

Is it because once the code find the first statement that is true, it dosent keep going?


#2

Yes, you are correct, the IF statement will exit on finding the first TRUE expression (or the ELSE expression of course).

If you place a breakpoint on the IF statement line, run the program, then when it stops on the statement [color=#008000]printf(“The first expression is true.”);[/color], click on Step Over, you will notice that it jumps to the end of the IF block.

Nick


#3

Thanks! :slight_smile: