1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Nested Conditional Constructs (TRACING) Confusion

  1. Sep 15, 2016 #1
    1. The problem statement, all variables and given/known data
    Manually
    trace the following code segments assuming that x equals 12. Show exactly what would be displayed on the terminal.

    Code (Text):
    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");
        }
    }
    2. Relevant equations
    Language: C

    3. 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
     
  2. jcsd
  3. Sep 15, 2016 #2

    phinds

    User Avatar
    Gold Member
    2016 Award

    The "if ... else" is embedded in the outer if. You need to learn to read parentheses (brackets in this case).
     
  4. Sep 15, 2016 #3
    Oh. Ya..... I am not sure how I didn't see that. It makes sense now. Thanks!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Nested Conditional Constructs (TRACING) Confusion
Loading...