Download presentation
Presentation is loading. Please wait.
Published byThomasina Avis Scott Modified over 8 years ago
1
CSC 162 Visual Basic I Programming
2
Repetition Structures Pretest Loop –Exit condition is tested before the body of code is executed Posttest Loop –Exit condition is tested after the body is executed at least once
3
Pretest Loops While/Wend or Do While/Loop Do Until/Loop For/Next
4
For Control_Variable = Initial_Value To Final_Value [Step Increment] Body_of_Loop Next Control_Variable Instead of having separate incrementing and condition checking statements, a For/Next loop combines both into the For statement. The Step is optional; it specifies the amount by which the Control_Variable is incremented. If left unspecified, it is assumed to be +1. While technically any data type is usable for the Control_Variable, it is best to use Integer data types. Strange things can happen otherwise. (See Example 3.)
5
Example 1 Dim intCounter As Integer Dim intSquare As Integer For intCounter = 0 To 10 intSquare = intCounter ^ 2 Print intCounter & " squared is " & intSquare Next intCounter Example 1 Execution
6
Example 2 Dim intCounter As Integer Print "Counting down from 21 by 3's" For intCounter = 21 To 14 Step -3 Print intCounter Next intCounter Example 2 Executionple 2 Execution
7
Example 3 Dim sngCounter As Single Print "Am I really counting by tenths?" For sngCounter = 0 To 1 Step 0.1 Print sngCounter Next sngCounter Example 3 Execution
8
Posttest Loops Do/Loop While Do/Loop Until
9
Do/Loop While Do Body_of_Loop Loop While Condition As long as the Condition is satisfied, the loop will continue to execute. Once the Condition is false, the code will resume execution after the Loop While statement.
10
Example Dim intCounter As Integer Dim intSquare As Integer intCounter = 0 Do intSquare = intCounter ^ 2 Print intCounter & " squared is " & intSquare intCounter = intCounter + 1 Loop While intCounter <= 10
11
Do/Loop Until Do Body_of_Loop Loop Until Condition As long as the Condition is not satisfied, the loop will continue to execute. Once the Condition is true, the code will resume execution after the Loop Until statement.
12
Example Dim intCounter As Integer Dim intSquare As Integer intCounter = 0 Do intSquare = intCounter ^ 2 Print intCounter & " squared is " & intSquare intCounter = intCounter + 1 Loop Until intCounter > 10
13
The Semicolon ; intNum = 2 Print intNum & " "; Print (intNum ^ 2) & " "; Print (intNum ^ 3) & " "; Print "That's it!" Output: 2 4 8 That's it! The semicolon keeps output on the same line. By itself, the Print statement outputs a single line.
14
What does this code produce? Dim intOuterCounter As Integer Dim intInnerCounter As Integer For intOuterCounter = 1 To 10 Step 2 For intInnerCounter = intOuterCounter To 1 Step -1 Print intInnerCounter; Next intInnerCounter Print Next intOuterCounter
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.