In: Computer Science
What are the key constructs required to create a loop? Identify two scenarios that may require two different types of loops. Be sure to provide specific details for each scenario that illustrate why the different types of loops are required.
In most languages we have 3 kinds of basic loops.
1. For loop
2. While loop
3. do-while loop
For loop and while loop are identical and interchangeable with no or little effort. These loops are entry control loops, that is loop condition is verified on entering. Since the condition is checked while entering the loop, it may happen that the body of the loop is not even executed.
Application of for loop:
Enter n, and print all numbers more than n but less than 100
in such cases is n > 100, no number is printed.
The other kind of loop is do-while loop. This loop is exit control loop, that is the condition is checked while exiting the loop. Since ther is no check while entering the loop, the body of the loop will be executed atleast once. While loop can be used as a do-while loop by intruducing a new variable.
Application of do-while loop:
Enter 1 to exit loop.
in such case the number is accepted within the body of the loop. and the condition is checked whille exiting the loop