05 May 2012

Loops with variable repetitions

'For' loops are controlled by a built-in counter and are used where the number of repetitions is known before the loops is executed. Some problems involve repetition based on a condition whose occurrence is unpredictable. For these problems,a pre-test loop is used with an appropriate condition.

A condition is a test which returns either true or false. Condition for loops are the same as those for selection statements, e.g.

value < 10    mark > 0    numb > 0 AND numb <= 100

A pre-test loop tests the condition at the beginning of the loop. A post-test loop tests the condition at the end.

When designing loops, make sure the loop control variable can change 'inside' the loop.

Pre-Test Loops

The purpose of a pre0test loop is to prevent the loop running if no processing is necessary. The standard Yourdon loop asks for input, tests a condition, then processes the input in a loop until the condition is met.

Get input
do while condition is true
    process data
    get input
end while
C Syntax
printf("Enter a positive number");
scanf("%d%*c", &Num);
while(Num > 0)
    //process data
    printtf("Enter a positive number");
    scanf("%d%*c", &Num);

Post-Test Loops

Post Test Loops must execute at least once.

While <condition>
C Syntax
} while(Num < 1);

No comments:

Post a Comment