Looping transforms intricate issues into simpler ones, allowing us to modify the program's flow. Rather than duplicating code repeatedly, we can iterate over it a set number of times. For instance, if we wish to display the initial 10 natural numbers, we can utilize a loop to achieve this task instead of repetitively using the printf statement 10 times.
Advantage of loops in C
1) It provides code reusability.
By utilizing loops, we can avoid repetitive coding tasks.
By employing loops, we have the ability to iterate through the components of data structures such as arrays or linked lists.
Types of C Loops
There are three variations of loops in the C programming language, as listed below:
-
- do while
-
- while
do-while loop in C
The do-while loop persists until a specified condition is met. This loop is alternatively known as a post-tested loop. It proves beneficial when there is a requirement to run the loop at least once, commonly seen in menu-driven applications.
Below is the structure of a do-while loop in the C programming language:
do{
//code to be executed
}while(condition);
Flowchart and Example of do-while loop
while loop in C
The while loop in C is employed when the exact number of iterations is unknown beforehand. The set of statements within the while loop is executed repeatedly until the condition defined in the while loop becomes true. This type of loop is also known as a pre-tested loop.
The format of a while loop in the C programming language is as follows:
while(condition){
//code to be executed
}
Flowchart and Example of while loop
for loop in C
The for loop is utilized when there is a requirement to repeat a portion of the code until a specific condition is met. This loop is alternatively referred to as a pre-tested loop. Opting for the for loop is advisable when the total number of iterations is predetermined.
The structure of a for loop in the C programming language is outlined as follows:
for(initialization;condition;incr/decr){
//code to be executed
}
Flowchart and Example of for loop