Nested Conditional Constructs (TRACING) Confusion

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 1K views
Marcin H
Messages
306
Reaction score
6

Homework Statement


Manually[/B] trace the following code segments assuming that x equals 12. Show exactly what would be displayed on the terminal.

Code:
if (x > 0) {
    printf("x>0\n");
    if (x < 10) {
        printf("x<10\n");
        if (x == 12) {
            printf("x==12\n");
        }
    }
    else {
        printf("Hello, world\n");
    }
}

Homework Equations


Language: C

The Attempt at a Solution


So looking at this code and going through it step by step I get that the output should just be x>0. Since x=12 the first line of code is right so the program should just stop there and print x>0 right? But when I test this out in an online compiler, it prints out x>0 and Hello World. Why does it do that? I thought that if the "if" part of an "if/else" statement is true then the code in the "if" will be executed and the rest won't mean anything. Why does the program continue on and print Hello World?

HERE IS THE LINK TO THE ONLINE COMPILER WITH THE CODE
 
Physics news on Phys.org
phinds said:
The "if ... else" is embedded in the outer if. You need to learn to read parentheses (brackets in this case).
Oh. Ya... I am not sure how I didn't see that. It makes sense now. Thanks!