User Tools

Site Tools


crawdad:programming:control

Control Statements

An executable program consists of a series of statements/instructions that the computer executes in order. Control statements influence this order, e.g. to repeat a series of instructions or to selectively skip or include others.

if-else Select different courses of action depending on a given set of conditions.

Example:

  if(iter >= maxiter) {
    cout << "Number of iterations exceeded.\n";
    exit(2);
  }
  else {
    cout << "iter = " << iter << endl;
  }

More information on such formatting strings will be given in a later section.

switch A multi-choice if statement.

Example:

  switch(val) {
    case 0:
      cout << "Zilch\n";
    case 1:
      cout << "Uno\n";
    case 2:
      cout << "Dos\n";
    case 3:
      cout << "Tres\n";
    default:
      cout << "A bunch\n";
      break;
  }
while Loop Repeat a series of instructions while the given conditions hold true.
Example:
  while(iter < maxiter) {
    x_coord += 2.0;
    iter++;
  }

Note that the value of iter must be initialized before the loop is carried out.

do-while Loop Similar to while, but the instructions are evaluated once before the conditional.

Example:

  do {
    x_coord += 2.0;
    iter++;
  } while(iter < maxiter);

This is just like the while loop above, except that energy and iter are incremented once before the comparison between iter and maxiter is made.

for Loop More sophisticated (and useful) loop involving initialization, conditional, and iteration.

Example:

  for(iter=0; iter < maxiter; iter++) {
    cout << "iter = " << iter << endl;
  }

Note that the arguments to the for loop consist of three components: (1) an initialization run before the loop starts (iter=0); (2) a condition that must hold true for the instructions to be carried out (iter < maxiter); and (3) a repeated instruction (iter++).

break Exit a loop or switch based on a given condition.

Example:

  for(iter=0; iter < maxiter; iter++) {
    energy += 2.0;
    cout << "iter = " << iter << endl;
    if(energy > 10.0) break;
  }

The break statement will exit the for-loop if the value of energy exceeds 10.0, even if iter < maxiter.

crawdad/programming/control.txt · Last modified: 2014/08/29 09:24 by crawdad