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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Private Sub cmdDisplay_Click()<br />

Dim pop As Single, yr As Integer<br />

‘Display population from 1998 to 2002<br />

picTable.Cls<br />

pop = 300000<br />

For yr = 1998 To 2002<br />

picTable.Print yr, FormatNumber(pop, 0)<br />

pop = pop + .03 * pop<br />

Next yr<br />

End Sub<br />

[Run, <strong>and</strong> click the comm<strong>and</strong> button.]<br />

The initial <strong>and</strong> terminating values can be constants, variables, or expressions. For<br />

instance, the For statement in the preceding program can be replaced by<br />

firstYr = 1998<br />

lastYr = 2002<br />

For yr = firstYr To lastYr<br />

In Example 1, the control variable was increased by 1 after each pass through the loop.<br />

A variation of the For statement allows any number to be used as the increment. The statement<br />

For i= m To n Step s<br />

instructs the Next statement to add s to the control variable instead of 1. The numbers m, n,<br />

<strong>and</strong> s do not have to be whole numbers. The number s is called the step value of the loop.<br />

EXAMPLE 2<br />

The following program displays the values of the index of a For...Next loop for terminating <strong>and</strong> step values<br />

input by the user.<br />

Object Property Setting<br />

frm6_3_2 Caption For index = 0 To n Step s<br />

lblN Caption n:<br />

txtEnd Text (blank)<br />

lblS Caption s:<br />

txtStep Text (blank)<br />

cmdDisplay Caption Display Values of index<br />

picValues<br />

Private Sub cmdDisplay_Click()<br />

Dim n As Single, s As Single, index As Single<br />

‘Display values of index ranging from 0 to n Step s<br />

picValues.Cls<br />

n = Val(txtEnd.Text)<br />

s = Val(txtStep.Text)<br />

For index = 0 To n Step s<br />

For...Next Loops 143

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

Saved successfully!

Ooh no, something went wrong!