CS111 Lab 4

No prelab.Prepare for exam 1 with practice problems and solutions

Objectives

Simple Programming Style Advanced Programming Idiom
if (condition1 == true) {
  expression1;
}
if (condition1) {
  expression1;
}
Former form is redundant. if (condition1) already means "if condition1 is true".
if (condition1 == false) {
  expression1;
}
if (!condition1) {
  expression1;
}
Former form is redundant.
if (condition1) {
  return true;
} else {
  return false;
}
return condition1;
We are just returning the result of the condition.
if (condition1) {
  expression1;
  return true;
} else {
  expression1;
  return false;
}
boolean result = condition1;
expression1;
return result;
We are just returning the value of the conditional and doing the same action regardless of its result. Therefore, we should store the result in a local variable.
if (condition1) {
  expression1;
} else {
  // do nothing
}
if (condition1) {
  expression1;
}
We are permitted to omit the "do nothing" else clause.
if (condition1) {
 // do nothing
} else {
  expression1;
}
if (!condition1) {
  expression1;
}
Essentially we want to do something if the condition is false.
if (condition1 && condition2) {
  expression1;
} else if (condition1 && !condition2) {
  expression1;
}
if (condition1) {
  expression1;
}
We are evaluating expression1 when condition1 is true, regardless of if condition2 is true or false. The check for the value of condition2 is unnecessary.
boolean result;
result = expression1;
boolean result = expression1;
Applies if the value of the variable is set only once and at the same level (not in any nested execution blocks like if-else statements).
boolean result = expression1;
return result;
return expression1;
Applies if the evaluation/declaration of the variable occurs right before the result is returned.

It is important to indent code properly and consistently in order for the code to be easy for others to read and understand. Three acceptable indentation styles are shown below. The form on the left is preferred since it is more compact.
expression1;
if (condition1) {
  expression2;
  if (condition2) {
    expression3;
  } else if (condition3) {
    expression4;
  } else {
    expression5;
  }
  expression6;
} else if (condition4) {
  expression7;
} else {
  expression8;
}
expression9;
expression1;
if (condition1)
{
  expression2;
  if (condition2)
  {
    expression3;
  } else if (condition3)
  {
    expression4;
  } else
  {
    expression5;
  }
  expression6;
} else if (condition4)
{
  expression7;
} else
{
  expression8;
}
expression9;
expression1;
if (condition1)
{
  expression2;
  if (condition2)
  {
    expression3;
  }
  else if (condition3)
  {
    expression4;
  }
  else
  {
    expression5;
  }
  expression6;
}
else if (condition4)
{
  expression7;
}
else
{
  expression8;
}
expression9;

Exercises