Your programming assistant #3: understanding loop statements
Loop statements allow a program to execute a set of instructions repeatedly until a specific condition is met or for a predetermined number of times. This can save time and reduce the amount of code needed to achieve a task. In the article about control flow we saw the basics of it, and now we're going deeper to understand how they work.
There are different types of loop statements in programming languages, such as the “while” loop, “for” loop, and “do-while” loop, among others. Each type of loop statement has its own syntax and behavior, but they all serve the same purpose of repeating a set of instructions until a certain condition is met.
While Loop
A while
loop executes a set of statements repeatedly as long as the specified condition is true. Here's an example in Python:
# Print all even numbers between 0 and 10
i = 0
while i <= 10:
if i % 2 == 0:
print(i)
i += 1
In this example, we use a while
loop to print all even numbers between 0 and 10. The loop starts by initializing a variable i
to 0. The condition for the while
loop is i <= 10
, which means the loop will continue as long as i
is less than or equal to 10.
Inside the loop, we use an if
statement to check if i
is even. If i
is even, we print its value using the print()
function. Finally, we increment the value of i
by 1 using the +=
operator.
This loop will execute as follows:
- The loop starts with
i
equal to 0. - The condition
i <= 10
is true, so the code block inside the loop is executed. i
is even, so we print its value (0).- We increment
i
to 1. - The condition
i <= 10
is still true, so the loop repeats. i
is odd, so we do not print its value.- We increment
i
to 2. - The condition
i <= 10
is still true, so the loop repeats. i
is even, so we print its value (2).- We increment
i
to 3. - … and so on, until
i
reaches 11 and the condition becomes false.
The output of this program will be:
0
2
4
6
8
10
For Loop
A for
loop is used to iterate over a sequence of values, such as a list, tuple, or string. Here's an example of a for loop in PHP:
// Print the numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
In this example, we use a for
loop to print the numbers from 1 to 5. The loop starts by initializing a variable $i
to 1. The condition for the for
loop is $i <= 5
, which means the loop will continue as long as $i
is less than or equal to 5.
Inside the loop, we use the echo
statement to output the value of $i
, followed by a space. Finally, we increment the value of $i
by 1 using the $i++
operator.
This loop will execute as follows:
- The loop starts with
$i
equal to 1. - The condition
$i <= 5
is true, so the code block inside the loop is executed. - We output the value of
$i
(1), followed by a space. - We increment
$i
to 2. - The condition
$i <= 5
is still true, so the loop repeats. - We output the value of
$i
(2), followed by a space. - We increment
$i
to 3. - … and so on, until
$i
reaches 6 and the condition becomes false.
The output of this program will be:
1 2 3 4 5
Do-While Loop
A do-while
loop is a loop that executes the code block at least once, and then repeats the loop as long as the specified condition is true. Here's an example in JavaScript:
// Prompt the user for a number and keep prompting until they enter a positive number
let input;
do {
input = parseInt(prompt("Enter a positive number:"));
} while (isNaN(input) || input <= 0);
console.log("You entered: " + input);
In this example, we use a do-while
loop to prompt the user for a positive number and keep prompting until they enter a valid input.
The loop starts by initializing a variable input
to undefined
. Then, we use a do
statement to execute the code block inside the loop at least once. Inside the loop, we use the prompt()
function to ask the user for a number, and then convert the user's input to an integer using the parseInt()
function. We use a logical OR operator (||
) to check if the input is not a number (isNaN(input)
) or if it's not positive (input <= 0
). If either condition is true, the loop continues and prompts the user again.
The loop will continue to prompt the user until they enter a valid positive number. When the user enters a valid input, the condition in the while
statement becomes false, and the loop exits. We then use the console.log()
function to output the user's input.
Here’s an example of how this program will execute:
- The loop starts with
input
equal toundefined
. - The code block inside the loop is executed, which prompts the user for a number and stores it in
input
. - If the user enters an invalid input (e.g., a non-numeric value or a negative number), the condition in the
while
statement is true, and the loop repeats. - If the user enters a valid input (e.g., 5), the condition in the
while
statement is false, and the loop exits. - We output the user’s input using the
console.log()
function.
The output of this program will be:
Enter a positive number:
[User enters "foo"]
Enter a positive number:
[User enters "-5"]
Enter a positive number:
[User enters "5"]
You entered: 5
Note that the program will continue to prompt the user until they enter a valid positive number.
Nested Loops
Nested loops are loops that are placed inside other loops. They are used when you need to iterate over a set of values multiple times, such as when working with matrices or multi-dimensional arrays. Here’s an example of a nested loop in Ruby:
# Print a multiplication table using nested loops
(1..10).each do |i|
(1..10).each do |j|
print "#{i * j}\t"
end
puts
end
In this example, we use nested loops to print a multiplication table from 1 to 10. We start with an outer loop that iterates from 1 to 10 using the each
method on a range object (1..10)
.
Inside the outer loop, we have an inner loop that also iterates from 1 to 10 using the each
method. For each pair of values i
and j
, we multiply them and print the result followed by a tab character \t
.
After the inner loop finishes executing for each value of i
, we use the puts
method to print a newline character \n
, which moves the cursor to the next line. This creates a new row for the multiplication table.
The output of this program will be:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
which is a 10x10 multiplication table. Each row represents a value of i
, and each column represents a value of j
.
These are the most common types of loops in programming. Each type of loop serves a different purpose, but they all allow you to execute a set of statements repeatedly under different conditions. See you in the next posts!