Sunday, June 23, 2024 22:24

## Nested loops

Nested loops are programming concepts consisting of two or more loops placed one into the other. The innermost loop is executed the most times, while the outermost, the least times. This is because the inner loops have to perform all of their cycling for every cycle of their next outer loop.

Lets exemplify this:

Running this code, the console will display:

Analyzing the code, we can see that we have an out loop, initializing an integer variable called x. This loop will increment our integer while its value is still less than 2; inside this loop, we have another loop, also declaring an integer, this time called y. As in our previous loop, this one will also increment its integer, but only while its value is less than 10. From the output, we can observe that the first loop only incremented its integer two times, while the inner loop has incremented it 20 times! I say 20 times, because, when the first loop started its first iteration, the inner loop ran 10 times, the interval from 0 to 9 (remember, our integer would be incremented while its still less than 10), then it ended its execution, and the outer loop started its second cycle, in which the inner loop will again increment its integer 10 times.

In conclusion, an inner loop will run ALL its cycles, for EVERY cycle of the outer loop.

The concepts explained in this lesson are also shown visually as part of the following video:

EXERCISES
1. Write a program that prints all possible cards from a standard deck of cards, without jokers (there are 52 cards: 4 suits of 13 cards).

Solution

Instrucțion: Number the cards from 2 to 14 (these numbers will match the cards 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A). Number the suits from 1 to 4 (1 – club, 2 – diamond, 3 – heart and 4 – spades). Now you can use the two nested loops and print each of the cards with two `switch` statements.

2. Write a program that reads from the console a positive integer number N (N < 20) and prints a matrix of numbers as on the figures below:

Solution

Instruction: You should use two nested loops. The outer loop must run from 1 to N, and the inner – from the value of the outer loop to the value of the outer loop + N – 1.

3. Write a program to display an asterisk pattern like a diamond

Solution

Tags: ,