Compound Conditional Statements

Many times there is more than one condition that must be TRUE in order for a loop to continue. By using the logical operators, && and ||, you can write compound conditionals:

int a = 1, b = 4;
while ( (a < 5) && (b > 2) )
{
  cout << setw(5) << a;
  cout << setw(5) << b;
  a++;
  b--;
}

Output:
    1    4
    2    3

There is no limit to how complex you can make the conditional. The real limit is in your understanding of the code. Be careful when using complex conditionals; they can be very difficult to find errors. It is very important to write detailed comments above your while loop conditional statements because:

   while ( (a == b) || (c > d) && ((e < c) || f) )

Can be impossible to understand long after you have written it, or even not so long after.

Previous slide
Next slide

Back to Lesson 9 Index
Back to Outline