In: Computer Science
1). Pre-Test loops:-
"Pre-Test loops are kind of loops where loop condition is get evaluated first and according to the condition result, block of code inside the loop is get executed."
For exampe:-
"for" loop
"while" loop
Lets analyze structure of "for" loop.
"for(<Intialization>; <condition>; <updation of conditional variabe>)"
where, Initialization happens only first execution of loop,
then condition gets evaluated,
If condition results in "true", code inside the loop gets executed.
then updation happens,
Again condition gets evaluated,
If condition results in true, code inside the loop gets executes, otherwise loop breaks.
2). C++ statements which uses pre-test loop:-
"for" and "while" are two statements which uses pre-test loop mechanism in C++.
I have explained the mechanism of "for" statement in previous section where i've defined pre-test loop,
"while" does same as "for". But unlike "for" Initialization always happens before "while" statement, while with "for", we have choice, either we can intialize loop variable before the "for" loop or inside the paranthesis of "for" loop.
structure of "while" loop,
<Initialization of variable>
while(<condition>) {
// loop body
<updation>
}
<updation> step can be anywhere inside the block of loop, either at the top of the code or in between or at the end of the block.
3). Pre-Test loops are also called 0 to N loops because they execute from 0 to N times. For example if loop condition results in false at first check then loop won't execute at all, in this case it will execute 0 times otherwise loop will execute until condition results in false, at most for N times, thats why it is called 0 to N loop.
4.) Whenever it is strictly required not to execute loop if condition results in false or whenever we require execute a logic if condition results in true, we use pre-test loops.
for example if we are asked to sum up numbers from 0 to some value let say 'n-1' and 'n' can be anything from 0 to some large number (100 or 10000 or 10000000 anything, greater than or equal to 0), we will pre-test loops. Let say if we are to find out the sum of first 10 natural numbers (1-10, here n = 11) then loop structure will be something like this,
ans = 0;
for(i = 1; i < 11; i++) {
ans += i;
}