19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The body of a For...Next loop can contain any sequence of <strong>Visual</strong> <strong>Basic</strong> statements. In particular,<br />

it can contain another For...Next loop. However, the second loop must be completely<br />

contained inside the first loop <strong>and</strong> must have a different control variable. Such a configuration<br />

is called nested loops. Figure 5-5 shows several examples of valid nested loops.<br />

FIGURE 5-5 Nested Loops<br />

EXAMPLE 4<br />

Write a program to display a multiplication table for the integers from 1 to 4.<br />

SOLUTION:<br />

In the following program, j denotes the left factors of the products, <strong>and</strong> k denotes the right factors. Each<br />

factor takes on a value from 1 to 4. The values are assigned to j in the outer loop <strong>and</strong> to k in the inner loop.<br />

Initially, j is assigned the value 1, <strong>and</strong> then the inner loop is traversed four times to produce the first row<br />

of products. At the end of these four passes, the value of j will still be 1, <strong>and</strong> the value of k will have been<br />

incremented to 5. The picTable.Print statement just before Next j guarantees that no more products will<br />

be displayed in that row. The first execution of the outer loop is then complete. Following this, the statement<br />

Next j increments the value of j to 2. The statement beginning For k is then executed. It resets the<br />

value of k to 1. The second row of products is displayed during the next four executions of the inner loop<br />

<strong>and</strong> so on.<br />

Private Sub cmdDisplay_Click()<br />

Dim j As Integer, k As Integer<br />

picTable.Cls<br />

For j = 1 To 4<br />

For k = 1 To 4<br />

picTable.Print j; “x”; k; “=”; j * k,<br />

Next k<br />

picTable.Print<br />

Next j<br />

End Sub<br />

Object Property Setting<br />

frmMultiply Caption Multiplication Table<br />

cmdDisplay Caption Display Table<br />

picTable<br />

For...Next Loops 145

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!