5.4 For Loops and Nested Loops

For Loops

A for loop takes a group of elements and runs the code within the loop for each element. This can be used to run a piece of code a certain number of times, or the operations can actually be based on the value. In Example 5-4, we see puts num is executed once for each value of num. That is, the loop will execute six times, and six lines with numbers 0 through 5 written one number per line will be generated. The range of values for num is defined by the construct 0..5 (see line 1), which represents all the integer values between 0 and 5 inclusive.

Example 5-4. For loop
    1 for num in (0..5)
    2 	puts num
    3 end

Nested Loops

A nested loop is a loop inside another loop. Although all kinds of loops can be nested, the most common nested loop involves for loops. These loops are particularly useful when displaying multidimensional data.

When using these loops, the first iteration of the first loop will initialize, followed by the second loop. The second loop will completely finish before the first loop moves on to its next iteration. If that sounds confusing, the example in Example 5-5 should help you understand the concept. Its corresponding flowchart is shown in Figure 5-4.

Example 5-5. Nested loop construct
    1 for i in (1..3)
    2 	puts "Outer loop: i = " + i.to_s
    3 for k in (1..4)
    4   puts "Inner loop: k = " + k.to_s
    5 	end
    6 end

If you execute the program presented, you will see that the outer loop is displayed three times. However, between each outer loop, four iterations of the inner loop are run.

The flowchart illustrates the internal computation necessary to execute the code presented. The code itself, however, is easier to follow than the actual flowchart. Note thus the essence of using the proper code structure for a particular task.

Nested loops can be a powerful tool when displaying data involving both rows and columns. For example, it is possible to make a program that would print a calendar that displays 12 different months, and for each month, displays each day.

Nested loop flowchart
Figure 5-4. Nested loop flowchart
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.255.87