Wednesday, August 26, 2009

Loops

Loops
  • Loop is to repeat the action over and over again
  • This condition to terminate or exit a loop is referred as loop control expression
  • C provide two looping statements namely: for, while and do...while

The while loop
  • pretest loop
  • It used an expression to control the loop
  • It test the expression before every iteration of the loop
       while (expression){
             Statements
       }
  • As long as the expression is evaluated to true the statements in the loop body will be repeated.

The for loop
  • a pretest loop
  • uses three expression
  • first expression contains initialization statements
  • the second contains the limit-test expression
  • the third contains the updating expression
  • A for loop is normally used when the number of times of the loop to be executed are knowns
       for(initialization; limit-test; updating){
             Statements;
       }
  • As long as the limit-test is evaluated to true the statements in the loop body will be repeated.

The do...while loop
  • a post-test loop
  • It also uses an expression to control the loop
  • It tests the expression after the execution of the body
  • The do…while loop end with a semicolon
  • The do…while loop only test the expression at the end of the loop, the body of the loop will be at least execute for once
       do{
              Statements;
       }while (expression);
  • As long as the expression is evaluated to true the statements in the loop body will be repeated.

No comments: