简体   繁体   中英

Conditional statement in C with nested if else else if

Found this code in a book:

if(a > b)
    if(c > b) printf("one");
    else if(c == a) printf("two");
    else printf("three");
else printf("four");

The question was: The program will never print
a. one b. two c. three d. four

The correct answer is b. two b. two

Here, I cannot understand why it will not print two , as in the condition given, c can equal a and c can be greater than b at the same time

If a is greater than b , and c is not greater than b , c can never be equal to a .

You can distribute the conditions:

one will print when a > b && c > b .

two will print when a > b && c <= b && c == a . Because of c == a , these conditions are equivalent to c > b && c <= b , which can never be true.

It is because of the else. Specifically, to get to that clause, a > b and c !> b (because if c > b, “one” would print). Thus, since c !> b, cb, then c != a, so “two” cannot be printed.

Another way to look at it, if you rewrite the code logically:

  • if a ≤ b , case "four"
  • if a > b AND c > b , case "one"
  • if a > b AND c ≤ b AND c = a , case "two"
  • if a > b AND c ≤ b AND c ≠ a , case "three"

The only case you can rewrite is the third bullet because with c = a you have:

if a > b AND c ≤ b AND c = a

which is logically equivalent to

if a > b AND a ≤ b

Which is never true for any value of a and b

you used else in 4 th and 5 th lines. you can not use else statment two times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM