Home >Web Front-end >JS Tutorial >Mastering the Art of Loops: Understanding For, While, and Do While Constructs Through Practical Examples
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 (start < end) { start++; }
Or
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.
The above is the detailed content of Mastering the Art of Loops: Understanding For, While, and Do While Constructs Through Practical Examples. For more information, please follow other related articles on the PHP Chinese website!