5.7.1. Making Decisions

If-statements

Statement
  if (condition)
  {
    statements1
  }
  else
  {
    statements2
  }  
starts by evaluating condition, an expression of type boolean. If the condition is true, then statements1 are performed. If the condition is false, then statements2 are performed. For example,
  if(x > 0)
  {
    y = x;
  }
  else
  {
    y = -x;
  }
ends with y equal to the absolute value of x.

Omitting the else-part

If you omit the word else and the compound statement that follows it, then nothing is done when the condition is false. For example,
  if(x < 0)
  {
    x = -x;
  }
will always end with x ≥ 0, since it does nothing if x ≥ 0.

Multiway tests

If you have more than two cases, use the following indentation scheme.
  if(test1)
  {
    …
  }
  else if(test2)
  {
    …
  }
  else if(test3)
  {
    …
  }
  else
  {
    …
  }

Watch out: semicolons

Be careful about semicolons. Statement
  if(n == 0);
  {
    System.out.printf("n is zero\n");
  }  
always writes "n is zero", regardless of the value of n. The semicolon at the end of the first line is an empty statement, so the if-statement says, if n equals 0, do nothing. The statement after that is just a compound statement. This really does two statements in a row.

The coding standards require you not to use a semicolon as an empty statement.


Making choices in expressions

Expression a ? b : c starts by evaluating expression a. If a is true (or nonzero), then it yields the value of expression b (and does not compute c at all). If a is false (or 0), it yields the value of expression c (and does not compute b at all). For example,
  int m = x > 0 ? x : -x;
creates variable m and stores the absolute value of x into m.

Only use this for expressions, not for statements. The coding standards require that.



Exercises

  1. Assume that integer variable n already has a value. Write a statement that makes m equal to 3n+1 if n is odd and to n/2 if n is even. Answer

  2. The coding standards forbid the following.

      if(n == 0){}
      else
      {
        z = 1;
      }
    
    Rewrite that into an acceptable form that does the same thing. Answer

  3. The coding standards disallow the following. Explain what is going on and how to avoid this.

      if(x == 0)
      {
        y = 1;
      }
      else if(x != 0)
      {
        y = 2;
      }
    
    Answer

  4. Suppose that you want to set y equal to

    Explain why the following does not do the job.

      if(x < 0)
      {
        y = -1;
      }
      if(x == 0)
      {
        y = 0;
      }
      else
      {
        y = 1;
      }
    

    Answer