Friday, July 13, 2012

Repetition and Looping (for loop , while loop)


Repetition means performing the same set of statements over and over.
The most common way to perform repetition is via looping.
A loop is a sequence of statements to be executed, in order, over and over, as long as some condition continues to be true.
while Loop
C has a loop construct known as a while loop:
        while (condition) {
            statement1;
            statement2;
            ...
        }
The condition of a while loop is a Boolean expression completely enclosed in parentheses – just like in an if block.
The sequence of statements between the while statement’s block open and block close is known as the loop body.



while Loop Behavior

while (condition) {
            statement1;
            statement2;
            ...
        }
A while loop has to the following behavior:
The condition is evaluated, resulting in a value of either true (1) or false (0).
If the condition evaluates to false (0), then the statements inside the loop body are skipped, and control is passed to the statement that is immediately after the while loop’s block close.
If the condition evaluates to true (1), then:
the statements inside the loop body are executed in sequence.
When the while loop’s block close is encountered, the program jumps back up to the associated while statement and starts over with Step 1.

while Loop Flowchart



               statement_before;
                      while (condition) {
                              statement_inside1;
                              statement_inside2;
                                  ...
                       }
               statement_after;









for Loop




                        for (counter = initial_value; counter <= final value; counter++) {
                                 statement1;
                                 statement2;
                                  ...
                        } /* for counter */
                        statement_after

No comments:

Post a Comment