Loops are a fundamental and highly important function in computer programming, playing an equally significant role in every programming language.
There are primarily three types of loops: 1. for 2. while 3. do while.
Let's first understand what a loop is. A loop is a construct that repeatedly executes a block of code based on a specified condition. You might wonder, "If a loop serves this purpose, why do we need three different types?" This is where a programmer's perspective comes into play, and this is our topic for today. Let's explore this through a story.
Imagine you are given two points: a starting point and an ending point. Additionally, you are told how much to increment each step from the start to the end. With these three conditions, we can create a loop known as a for loop.
To simplify, consider that Sajib wants to print even numbers from 10 to 100. He would need to go 10, 12, 14, and so on. Here, 10 is the starting point, 100 is the ending point, and the increment is 2, as we move two steps each time. This task can easily be done using a for loop.
Basic syntax:
for (start; end; increment) { // loop body }
Those familiar with loops might say, "We can do this with a while or do while loop too!" Yes, we can, but we need to consider which type is more convenient for the task at hand.
While Loop
The word "while" in English means "as long as." Simply put, the loop will execute as long as the condition remains true.
To explain further, as long as the starting point is less than the ending point, or if the loop is reversed, as long as the ending point is less than the starting point, the loop will execute. In while and do while loops, the increment or decrement operation is performed within the loop body.
Basic syntax:
while (startOr
while (end > start) { end--; }Note that with a while loop, we can run an infinite loop based on a condition and then stop it with another condition.
Do While Loop
The mechanism of the do while loop is fundamentally the same as the while loop. We use a do while loop specifically when we need the program to execute at least once, even if the condition is false.
I hope this discussion has given you a clear understanding of the three types of loops. Now, practice extensively in real-life scenarios to make everything easier for you.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3