Nested Loops

What are nested loops?

You can use nested loops. To do this, you have to put one of them as a body (or as a part of the body) of the other:

Nested loops definition


We say that "the inner is nested inside the outer”. For each step of the outer part, the inner executes all its steps.

Examples and explanations

Let's create a program, which outputs the numbers from 10 to 99, using two number variables.

Simple exmaple with nested loops

Note: So far all variables that we used had descriptive names. It is very popular practice that counter variables are assigned short names such as i,j,k etc. Sometimes we will use such names, so that you get used to it and read easier code from other programmers.

In this example first “i” takes the value 1. Then it is compared to the number 9. If “i” is not smaller than or equal to 9 the program ends. 1 is less than 9, so we enter the body ; j = 0, 0< 10 => we enter the body of the nested(inner) loop and the program outputs the values of our variables: 10. Next j++ increments j to the value of 1. Now we continue with step two of the inner part. Since 1 is less than 10, the inner body will execute again and the program will output 11. We will print 12,13.. 19. When “j” reaches the value 10, the inner condition
(i < 10) will return false and we increment “i” with “i++”.

At this moment “i” is 2, which is less than 9, so we enter the loop again. j = 0, 0 < 10, we print ij (20). j++, 1 < 10, print 21 … until we print all numbers until 29. Then we increment "i" and return to the outer condition and this will continue until the it returns false (when i = 10). At this moment the program finishes successfully.

One more example: create a program which outputs all fields' notation from of a chess board. A chess board contains 64 squares (8x8). The 8 horizontals are numbered 1-8 and the verticals are A-H. This means we have to output the combinations A1-A8, B1-B8...H1-H8.

This is similar to what we did in the last example. The difference is that we have to output a combination of a character and a number (in the last example we combined to numbers).

Lets recall what is the character type. It keeps information for a single symbol. That symbol is represented with numeric code. If you forgot this you can review the data types lesson.

Now, not only the chars are represented by numbers, but also they are ordered in an ascending order. For instance, if the code of 'A' is 65, then the code of 'B' is 66.

The next good news is that we can do our arithmetic with a char variable, just like we do with a number variable. This means that we can increment it, using the ++ operator, we can compare a char variable to a number and we can compare it to another char variable. For example 'A' < 'B' is a valid comparison and the result is true, because the code of 'B' (66) is greater than the code of 'A' (65).

Using nested loops to print all chess squares

Example: Output all combinations of three numbers in the range of 1-20.

Maybe you guessed it, but we will need 3 nested loops for this task.

3 nested loops

Take your time and try to figure out how this algorithm works. Try to follow it step by step.

Probably you noticed, that using nested loops, the number of actions, that our program does increases very rapidly. In the last example the output in the inner most block will execute 20x20x20 = 8000 times. This means more time for the execution of our program. So, be careful, when nesting multiple loops.

There is no limit how many loops we can nest, but if you need more than 3, then most likely you need to optimize your algorithm. In fact it is rare case to need more than 2.

Homework

Write a program, using nested loops that:

  1. outputs all combinations 19, 18, 17... 92, 91, 90
  2. prints all capital letters from the alphabet and their positions: A = 1, B = 2... Z = 26
  3. *.. prints a rectangle, drawn by the symbol '*'. Each side is 10 *.
    The output should look like this:
    *    *    *    *    *    *    *    *    *    *
    *                                               *
    *                                               *
    *                                               *
    *                                               *
    *                                               *
    *                                               *
    *                                               *
    *                                               *
    *    *    *    *    *    *    *    *    *    *

    Helper1: When you normally output symbols, they are on the same row. To start printing on the next row you need to output the symbol for a new row.

    Helper2: The symbol for new line is '\n' (backslash n);

Previous: Loops

Next: Arrays

Tutorial Contents:

1)Learn Computer Programming
2)Software Development Process
3)Flow Chart
4)Flow Chart Symbols
5)Data Type
6)What is a variable
7)Math Operators
8)Logical Operators
9)Loops

10)Nested Loops
11)Arrays
12)Multidimensional arrays
13)Programming Questions

   Search this site: