Loops
A loop is a programming structure that allows an action to repeat until the program meets a given condition.
After each iteration of a loop, the loop checks against a loop control expression to see if the program meets the given condition. If the given condition is met with, then the loop moves to the next iteration. If not, the loop stops.
In simple words, loops allow the program to repeat a section of code any number of times until the condition occurs.
Types of Loops
‘C’ program, supports two categories of loops based on where the program tests the condition:
Pre-test Loop
With each iteration, the program tests the condition first before executing the loop’s block.
If the condition is true, the loop continues and executes the block; if the condition is false, the loop terminates.
With a pre-test loop, there is a chance that, the loop may not execute.
Operation
When the test takes place at the top of the loop, it is said to be a pre-test loop.
In each iteration of the pre-test, the condition is tested first.
Loop Initialization
Program typically requires some type of preparation before executing loops.
Loop initialization, which happens before a loops first iteration, is a way to prepare the loop. It may be explicit or implicit.
In explicit initialization, we write codes to set the values of key variables used by the loop.
Implicit initialization relies on a “pre-existing situation to control the loop”.
Updating a Loop
A loop update is what happens inside a loops block that eventually causes the loop to satisfy the condition, thus ending the loop.
Updating, happens during each loop iteration.
Without a loop update, the loop would become an infinite loop.
Initializing and Updating
Here, the condition is tested first, and then the action takes place.
After the action the loop iteration is updated.
Event Controlled Loops
In an event-controlled loop, an event is something that happens in the loops execution block that changes the loops control expression from true to false.
The program can update the loop control expression explicitly or implicitly.
We cannot predict the number of iterations during the run of a program.
In an event-controlled loop pre-test loop, the condition is tested first.
If the condition is true, then the action and iterations takes place.
If the condition is false, the loop terminates.
Counter-controlled Loops
In a counter-controlled loop, the number of loop iterations can be controlled.
In such a loop, we use a counter, which we must initialize, update and test.
The number the loop assigned to the counter does not need to be a constant value.
To update, we can increment or decrements the counter.
In counter-controlled pre-test loop, the counter is initialized, updated and tested.
The value given in the counter need not be of a constant value.
The number of iterations can be controlled here.