Program Control : REPETITION

Program Control : REPETITION

Sub Topics :

  • Repetition Definition
  • For
  • While
  • Do-While
  • Repetition Operation
  • Break vs Continue
Repitition Definition
  • One or more instruction repeated for certain amount of time
  • Repetition/looping operation ;
    • for
    • while
    • do-while

Repetition : FOR
exp1 and exp3 can consist of several expression separated with comma
Example:
void reverse(char ss[])
{
    int c,i,j;
    for(i=0, j=strlen(ss)-1; i<j; i++, j--){
        c=ss[i];
        ss[i]=ss[j];
        ss[j]=c;
    }
}
  • Infinite Loop
    • Loop withh no stop condition can use "for-loop" by removing all parameters (exp1, exp2, exp3). To end the loop use break.
  • Nested Loop
    • Loop in a loop. The repetition operation will start from inner side loop.

Repetition : WHILE
while (exp) statements;
  • exp is boolean expression. The result will be true (not zero) or false (zero).
  • statement will be executed while the exp is not equal to zero (true).
  • exp evaluation is done before the statements executed.

Repetition : DO-WHILE
Example :
     int counter=0;
     do {
          printf( "%d  ", counter );
       ++counter;
     } while (counter <= 10);
  • while exp is true, keep executing
  • exp evaluation done after executing the statement(s)

Repetition : OPERATION
  • In while operation, statement block of statements may never be executed at all if exp value is false
  • In do-while on the other hand statement block of statements will be executed min once
  • To end the repetition, can be done through several ways:
    • Sentinel
    • Question, should the repetition continue
BREAK vs CONTINUE
  • Break :
    • ending loop (for, while, and do-while)
    • end the switch operation
  • Continue : skip all the rest of statements inside a repetition and continue normally to the next loop








Comments