Matching if's and else's

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

What suffix is chosen if (count+1) is equal to 5?

Answer:

suffix = "th";

Matching if's and else's

Here is how the nested if works when (count+1) is equal to 5:

if ( count+1  == 2  )      <--- false: go to false branch
  suffix = "nd";
else 
  if ( count+1 == 3  )     <--- false: go to inner false branch
    suffix = "rd";
  else
    suffix = "th";         <--- inner false branch exectued

When (count+1) is 4 or greater the "th" suffix will be chosen.

It is sometimes hard to see exactly how the if's and else's nest in programs like this. Braces can be used to show what matches what, but lets starts with a rule that does not talk about that. The rule is:

Start with the first if and work downward. Each else matches the closest previous unmatched if. An if matches only one else and an else matches only one if.

You should indent the program to show this, but remember that the compiler does not pay any attention to indenting. Here is the program fragment again showing the matching ifs and elses.

if ( count+1  == 2  )
  suffix = "nd";
else 
  if ( count+1 == 3  )
    suffix = "rd";
  else
    suffix = "th";

The "if" and "else" of a matching pair are part of one "if statement." For example, the red pair above make are part of one statement so the over-all structure of the program fragment is:

if ( count+1  == 2  )
  suffix = "nd";
else 
  false branch 

Here is another example. It is not indented properly. Use the rule to figure out which ifs and ifs match.

if ( a == b )
  
if ( d == e )
  total = 0;
  
else
  total = total + a;

else
  total = total + b;

QUESTION 12:

Match the ifs and elses.