The if . . . else Statement

Format of the if . . . else statement:

  if (<boolean expression>)
    <statement 1>
  else
    <statement 2>

Example code fragment:

if (denominator != 0)
    ratio = numerator / denominator;
else
    cout << "Can't divide by zero.";

Example Function:

int calculateMax(int num1, int num2)
{
    if (num1 > num2)   // if num1 > num2
        return num1;   //   num1 is larger
    else               // otherwise
        return num2;   //   num2 is larger
}                      

Note: If num1 == num2, then it doesn't matter which one you return as the larger one. They are both considered to be the larger.

Next page
Previous page
Go to Lesson 7 index.


HTML by Jennifer Keiser.
Sponsored by Inspiration, the diagramming and outlining tool.