(Lesson 6) Nested Loops
(Lesson 6) Nested Loops
A loop can contain any kind of statement(s) inside its body, including
another loop. One loop inside another is called a nested loop.
The counter variable of the inner loop should have a different name,
so that it will not conflict with the outer loop.
A nested loop has the following syntax, as an example:
Keep in mind that the outer loop controls number of lines (i.e. rows),
and the inner loop controls content of these lines (i.e. columns).
Drawing figures can illustrate how nested loops work…
Wow! Let’s start drawing these figures using
nested loops ☺
Example (1): A Simple Figure
In the shown example, the first thing to do is to ask yourself, how many rows and
how many columns do you have?
You have 6 rows and 10 columns. So, the outer loop counts from 1 to 6, and the inner
loop counts from 1 to 10.
Example (1) explanation
The outer loop controls the number of rows, and the
inner loop controls the number of columns.
This means that for each of the 6 rows, there are 10
columns.
At each column, an asterisk (*) is printed. All 10
asterisks are printed beside each other.
After the inner loop finishes its 10 rounds, the
program then makes a new line <br>.
The outer loop now starts its 2nd round, and again
the inner loop is repeated 10 times in the same
exact way, and so on.
Example (2): An Emojis Figure
Now, let’s remove the asterisk in the previous example, and simply
put an image instead.
Note: you must have an image called “angel.png” stored at the same path of your program
Example (3): More interaction (input)
How about asking the user to enter the number of rows and the
number of columns of the figure…
Example (3): More interaction (input)
Example (3): More interaction (input)
PHP Program (example3.php)
Example (4): Switching Emojis
The user is asked to enter the number of rows and columns, and
accordingly the program prints the times table of all numbers.
Example (8): Multiplication Table