In programming, loops are fundamental tools used to perform repetitive tasks. They allow you to execute a block of code multiple times without having to write it over and over. Today, we'll dive into the most common types of loops—while, do-while, and for loops—as well as jumping statements like break and continue. These concepts are key to writing efficient and clean code.
1. While Loop
The while loop is a basic looping construct that runs as long as a specified condition is true. If the condition is false at the beginning, the loop will not execute at all.
Syntax:
while (condition):
# Code to be executed
Example:
i = 0
while i < 5:
print(i)
i += 1
In this example, the loop continues to run as long as i is less than 5. Once i reaches 5, the condition becomes false, and the loop terminates.
2. Do-While Loop
The do-while loop is similar to the while loop, but the key difference is that it executes at least once, regardless of the condition. This is because the condition is checked after the code inside the loop is executed.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
(in C/C++/Java):
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
In this example, the loop runs at least once, even if i is initially 5, since the condition is checked after the execution of the code block.
3. For Loop
The for loop is the most compact form of looping. It is typically used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.
Syntax:
for initialization; condition; increment/decrement:
# Code to be executed
Example:
for i in range(5):
print(i)
Here, i takes values from 0 to 4, and the loop executes exactly 5 times. This loop is ideal when you know the exact number of iterations ahead of time.
4. Jumping Statements
In certain situations, you might want to prematurely exit a loop or skip the execution of certain iterations. For this, we have jumping statements like break and continue.
A. Break Statement
The break statement is used to exit the loop entirely when a certain condition is met, regardless of whether the loop condition is still true.
Example:
for i in range(10):
if i == 5:
break
print(i)
In this case, the loop will terminate when i equals 5, and the numbers 0 to 4 will be printed.
B. Continue Statement
The continue statement skips the current iteration of the loop and proceeds with the next iteration.
Example:
for i in range(5):
if i == 3:
continue
print(i)
In this example, when i equals 3, the continue statement skips the rest of the loop's body and proceeds with the next iteration, meaning the number 3 will not be printed.
5. Practical Example Combining Loops and Jumping Statements
for i in range(1, 11):
if i == 5:
print("Skipping 5")
continue
if i == 8:
print("Terminating loop at 8")
break
print(i)
This loop prints the numbers from 1 to 10 but skips 5 and stops the loop entirely at 8.