72
1 Visual Basic Programming AUBG Spring semester 2011 Reference books: Schneider D., An Introduction to Programming Using Visual Basic, Prentice Hall, Pearson Education Inc., 7th Ed. 2008, 6th Ed. 2006 Liberty J., Learning Visual Basic .NET, O’Reilly, 2002 Any Visual Basic book available in AUBG library Course lecturer: Assoc. Prof. Svetla Boytcheva, PhD

INF110 Visual Basic Programming AUBG Spring semester 2011

  • Upload
    seth

  • View
    16

  • Download
    0

Embed Size (px)

DESCRIPTION

- PowerPoint PPT Presentation

Citation preview

Page 1: INF110 Visual Basic Programming  AUBG Spring semester 2011

1

INF110Visual Basic Programming

AUBG Spring semester 2011

Reference books:Schneider D., An Introduction to Programming Using Visual Basic, Prentice Hall, Pearson Education Inc., 7th Ed. 2008, 6th Ed. 2006 Liberty J., Learning Visual Basic .NET, O’Reilly, 2002 Any Visual Basic book available in AUBG library

Course lecturer: Assoc. Prof. Svetla Boytcheva, PhD

Page 2: INF110 Visual Basic Programming  AUBG Spring semester 2011

2

INF110 Visual Basic Programming AUBG Spring semester 2011

Lecture 7Title:

Visual Basic(Repetition/Iteration

statements 1)

Page 3: INF110 Visual Basic Programming  AUBG Spring semester 2011

3

Lecture Contents:

Repetition/Iteration statements:Pre Test LoopsPost Test LoopsLogically Controlled LoopsCounter Controlled LoopsNested Loops

Page 4: INF110 Visual Basic Programming  AUBG Spring semester 2011

4

Quiz 2on

Decision Operators and Expressions

Page 5: INF110 Visual Basic Programming  AUBG Spring semester 2011

5

Control Structures IIControl Structures II

RepetitionRepetition

(aka Iteration)(aka Iteration)

INF110

Visual Basic Programming

Page 6: INF110 Visual Basic Programming  AUBG Spring semester 2011

6

An iterative statement is one which executes one or more other statements a certain number of times

i.e. the execution of one or more statements is repeated

The iterative statement comes in a variety of “flavours”.

They are used for a number of purposes, such as:• searching a collection of data items for one with a specific value, or• performing a calculation involving a collection of data items (e.g. adding them all together to get a total) or• performing some action repeatedly until an event occurs which tells it to stop (imagine a robot placing boxes on a conveyor belt ...)

Page 7: INF110 Visual Basic Programming  AUBG Spring semester 2011

7

• Repetition statements (also iterative statements) may classify in two sub groups:

Do…Loop statements

For…Next statements

Page 8: INF110 Visual Basic Programming  AUBG Spring semester 2011

8

Do Loops

• A loop is one of the most important structures in programming.

• Used to repeat a sequence of statements a number of times.

• The Do loop repeats a sequence of statements either:• as long as, a certain condition is True.• until, a certain condition becomes True.

• It has a few variants …

Page 9: INF110 Visual Basic Programming  AUBG Spring semester 2011

9

Comments

• Be careful to avoid infinite loops – loops that never end.

• VB.NET allows for the use of either the While keyword or the Until keyword at the top or the bottom of a loop. We will mostly use While at the top of a loop (pretest loop) and Until at the bottom of a loop (posttest loop).

• Semantics:

“Do these actions while condition is true”

or

“Do these actions until a condition becomes true”

Page 10: INF110 Visual Basic Programming  AUBG Spring semester 2011

10

•Variations of the Do…Loop control structure:

Do … Loop1/ Pre test loops

with While and Until

2/ Post test loops

with While and Until

Page 11: INF110 Visual Basic Programming  AUBG Spring semester 2011

11

Do LoopsDo While boolean expression

statementsLoop------------------------------------------Do Until boolean expression

statementsLoop------------------------------------------Do

statementsLoop While boolean expression------------------------------------------Do

statementsLoop Until boolean expression------------------------------------------Do

statementsLoop

Page 12: INF110 Visual Basic Programming  AUBG Spring semester 2011

12

Do Loops in VBasic

Pretest loops

----------------------------------------- Do While boolean expressionstatements

Loop-----------------------------------------Do Until boolean expressionstatements

Loop-----------------------------------------

Page 13: INF110 Visual Basic Programming  AUBG Spring semester 2011

13

Do Loops in VBasic

Posttest loops

-----------------------------------------Do statements

Loop While boolean expression-----------------------------------------Do statements

Loop Until boolean expression-----------------------------------------

Page 14: INF110 Visual Basic Programming  AUBG Spring semester 2011

14

Do Loops in VBasic

Infinite /endless/ loops

-----------------------------------------Do statements

Loop -----------------------------------------

Page 15: INF110 Visual Basic Programming  AUBG Spring semester 2011

15

Do While <condition> … Loop

Statement

Page 16: INF110 Visual Basic Programming  AUBG Spring semester 2011

16

Do While … Loop Syntax

Do While condition

statement(s)

Loop

Condition is tested.If it is True,

the loop is run.If it is False,

the statements following the Loop statementare executed.

These statements are inside the body of the loop and are run if the condition

above is True.

condition is a Boolean expression

Page 17: INF110 Visual Basic Programming  AUBG Spring semester 2011

17

Pseudocode and Flow Chart for a Do Loop

Page 18: INF110 Visual Basic Programming  AUBG Spring semester 2011

18

Dim Counter As Integer = 20Do While Counter <= 100

Console.Writeline(Counter)

Counter = Counter + 10

Loop

The above example will keep on adding until Counter’s value becomes > 100

Page 19: INF110 Visual Basic Programming  AUBG Spring semester 2011

19

Example

Dim PassWord As String

PassWord = “”

Do While PassWord <> “SHAZAM”

Console.Writeline(“Enter password:")

PassWord = Console.Readline()

Loop

PassWord is the loop control variable because the value stored in PassWord

is what is tested to determine if the loop should continue or stop.

Page 20: INF110 Visual Basic Programming  AUBG Spring semester 2011

20

‘Accumulate sum of the numbers from 1 to 7

Dim Num As Integer = 1 Dim Sum As Integer = 0

Do While Num <= 7 Sum = Sum + Num Num = Num + 1 'Add 1 to the value of Num Loop

Page 21: INF110 Visual Basic Programming  AUBG Spring semester 2011

21

Do … Loop Until <condition>

Statement

Page 22: INF110 Visual Basic Programming  AUBG Spring semester 2011

22

Do … Loop Until

Do

statement(s)

Loop Until condition

Loop is executed once and then the conditionis tested. If it is False, the loop is run again.

If it is True, the statements following the Loop statement are executed.

Since the condition is tested at thebottom the loop, the loop will

execute at least once.

Page 23: INF110 Visual Basic Programming  AUBG Spring semester 2011

23

Pseudocode and Flowchart for a Do … Loop Until

Page 24: INF110 Visual Basic Programming  AUBG Spring semester 2011

24

Dim Counter As Integer = 20

Do Console.Writeline(Counter) Counter = Counter + 10

Loop Until Counter > 100

Page 25: INF110 Visual Basic Programming  AUBG Spring semester 2011

25

Example

Dim PassWord As String

Do

Console.Writeline(“Enter password:")

PassWord = Console.Readline()

Loop Until PassWord = "SHAZAM"

Page 26: INF110 Visual Basic Programming  AUBG Spring semester 2011

26

Nested Loops

Statements inside a loop can contain another loop.

(Just like If statements).

Example: What is the output of this code?i = 0

Do While i < 6

j = 0

Do While j < 6

Console.Write("*")

j = j + 1

Loop

Console.WriteLine()

i = i + 1

Loop

Nested loops are quite common, especially for processing tables of data.

Assume initially that i = 0

Page 27: INF110 Visual Basic Programming  AUBG Spring semester 2011

27

Nested Loops

Statements inside a loop can contain another loop.

(Just like If statements).

Example: What is the output of this code?i = 0

Do While i < 6

j = 0

Do While j < i

Console.Write("*")

j = j + 1

Loop

Console.WriteLine()

i = i + 1

Loop

Nested loops are quite common, especially for processing tables of data.

Assume initially that i = 0

Page 28: INF110 Visual Basic Programming  AUBG Spring semester 2011

28

When condition is a variable of Boolean type,

the statements likeIf flagVar = True Then ...

can be replaced byIf flagVar Then ...

and

the statements likeIf flagVar = False Then ...

can be replaced byIf Not flagVar Then ...

Page 29: INF110 Visual Basic Programming  AUBG Spring semester 2011

29

The statements like

Do While flagVar = True

can be replaced by

Do While flagVar

and

The statements like

Do While flagVar = False

can be replaced by

Do While Not flagVar

Page 30: INF110 Visual Basic Programming  AUBG Spring semester 2011

30

The iterative statement

Do While condition

statement(s)

Loop

Has an alternative while control structure:

The While repetition structure

Page 31: INF110 Visual Basic Programming  AUBG Spring semester 2011

31

While Repetition Structure

• Repetition structure

– Allows the programmer to specify that an action should be repeated, depending on the value of a condition.

• Example (pseudocode)

While there are more items on my shopping list

Purchase next item

Cross it off my list

Just like Do While ... loop

Page 32: INF110 Visual Basic Programming  AUBG Spring semester 2011

32

Dim Product As Integer = 2 While Product <= 1000

Console.Writeline(Product)Product = Product * 2

End While

The decision is tested each time the loop iterates

product <= 1000

true

product = product * 2

false

Page 33: INF110 Visual Basic Programming  AUBG Spring semester 2011

33

‘ Modern VB 2005/2008 versionDim Product As Integer = 2While Product <= 1000

Console.Writeline(Product)Product = Product * 2

End While

VB6 >>> VB 2005/2008The End While statement replaces the Wend statement of VB6.

‘ Obsolete VB 6 versionDim Product As Integer = 2While Product <= 1000

Console.Writeline(Product)Product = Product * 2

WEnd

Page 34: INF110 Visual Basic Programming  AUBG Spring semester 2011

34

Nested Loops using While … End While control structure

Statements inside a loop can contain another loop.

Example: What is the output of this code?

i=0

While i < 6

j = 0

While j < 6

Console.Write("*")

j = j + 1

End While

Console.WriteLine()

i = i + 1

End While

Nested loops are quite common, especially for processing tables of data.

Assume initially that i = 0

Page 35: INF110 Visual Basic Programming  AUBG Spring semester 2011

35

Nested Loops using While … End While control structure

Statements inside a loop can contain another loop.

Example: What is the output of this code? i=0

While i < 6

j = 0

While j < i

Console.Write("*")

j = j + 1

End While

Console.WriteLine()

i = i + 1

End While

Nested loops are quite common, especially for processing tables of data.

Assume initially that i = 0

Page 36: INF110 Visual Basic Programming  AUBG Spring semester 2011

36

Do Loops• All the variations use the same basic model.

A pretest loop is executed either– While the condition is True. Uses While

reserved wordDo While conditionstatement-block

Loop

– Until the condition becomes True. Uses Until reserved wordDo Until conditionstatement-block

Loop

Page 37: INF110 Visual Basic Programming  AUBG Spring semester 2011

37

Examples

I = 1

Do While (I <= 10)

Console.WriteLine(I)

I = I + 1

Loop

How many iterations are to be run? (10) Try it

Page 38: INF110 Visual Basic Programming  AUBG Spring semester 2011

38

Examples

I = 1

Do Until I <= 10

Console.WriteLine(I)

I = I + 1

Loop

How many iterations are to be run? (0) Try it

Page 39: INF110 Visual Basic Programming  AUBG Spring semester 2011

39

Examples to achieve the same effectI = 1Do While (I <= 10)

Console.WriteLine(I)I = I + 1

Loop======================= same effectI = 1Do Until Not(I <= 10)

Console.WriteLine(I)I = I + 1

Loop

How many iterations are to be run? (10) Try it

Page 40: INF110 Visual Basic Programming  AUBG Spring semester 2011

40

Examples to achieve the same effectI = 1Do While Not(I <= 10)

Console.WriteLine(I)I = I + 1

Loop======================= same effectI = 1Do Until (I <= 10)

Console.WriteLine(I)I = I + 1

Loop

How many iterations are to be run? (0) Try it

Page 41: INF110 Visual Basic Programming  AUBG Spring semester 2011

41

Post test loops with While and Until

Page 42: INF110 Visual Basic Programming  AUBG Spring semester 2011

42

Do Loops• All the variations use the same basic model.

A posttest loop is executed either– While the condition is True. Uses While

reserved wordDostatement-block

Loop While condition

– Until the condition becomes True. Uses Until reserved wordDostatement-block

Loop Until condition

Page 43: INF110 Visual Basic Programming  AUBG Spring semester 2011

43

Examples

I = 1

Do

Console.WriteLine(I)

I = I + 1

Loop While (I <= 10)

How many iterations are to be run? (10) Try it

Page 44: INF110 Visual Basic Programming  AUBG Spring semester 2011

44

Examples

I = 1

Do

Console.WriteLine(I)

I = I + 1

Loop Until (I <= 10)

How many iterations are to be run? (1) Try it

Page 45: INF110 Visual Basic Programming  AUBG Spring semester 2011

45

Examples to achieve the same effect

I = 1Do

Console.WriteLine(I)I = I + 1

Loop While (I <= 10)=================== same effectI = 1Do

Console.WriteLine(I)I = I + 1

Loop Until Not(I <= 10)

How many iterations are to be run? (10) Try it

Page 46: INF110 Visual Basic Programming  AUBG Spring semester 2011

46

Examples to achieve the same effect

I = 1Do

Console.WriteLine(I)I = I + 1

Loop While Not(I <= 10)=================== same effectI = 1Do

Console.WriteLine(I)I = I + 1

Loop Until (I <= 10)

How many iterations are to be run? (1) Try it

Page 47: INF110 Visual Basic Programming  AUBG Spring semester 2011

47

Endless loops

with While … End While

andDo … Loop

Page 48: INF110 Visual Basic Programming  AUBG Spring semester 2011

48

Endless loops - examples

While True

statement-block

End While

Page 49: INF110 Visual Basic Programming  AUBG Spring semester 2011

49

Endless loops - comments

The endless loops should be avoided. They must be terminated from within the own loop body with an Exit statement

While True statement-block

if condition Then Exit Whilestatement-block

End While

Page 50: INF110 Visual Basic Programming  AUBG Spring semester 2011

50

Endless loops - examples

Do

statement-block

Loop

Page 51: INF110 Visual Basic Programming  AUBG Spring semester 2011

51

Endless loops - comments

The endless loops should be avoided. They must be terminated from within the own loop body with an Exit statement

Dostatement-blockIf condition Then Exit Dostatement-block

Loop

Page 52: INF110 Visual Basic Programming  AUBG Spring semester 2011

52

From Logically controlled loop

ToCounter controlled loop

Introduction to

For … Next Loop statement

Page 53: INF110 Visual Basic Programming  AUBG Spring semester 2011

53

You use a Do loop when you do not know how many times the statements should be run.

If you know that they should be run for a specific

number of times, then use a For … Next loop.- coming on next slides!

This loop variant uses a counter which increases or decreases on each repetition of the loop and the looping ends when this counter reaches a set value.

Page 54: INF110 Visual Basic Programming  AUBG Spring semester 2011

54

For … Next Loops

• Used when we know how many times we want the loop to execute.

• A counter-controlled loop

Page 55: INF110 Visual Basic Programming  AUBG Spring semester 2011

55

For … Next Loop Syntax

The format is:

For counter = startNumber To endNumber Step increment

    One or more VB statements

Next

starts with counter = startNumber and increments counter each time through the loop by an amount equal to increment until it reaches endNumber.

The bounds (startNumber, endNumber) are integer quantities, and Step controls the increments (which may be negative).

Page 56: INF110 Visual Basic Programming  AUBG Spring semester 2011

56

For … Next Loop Syntax

One more format is:

For counter = startNumber To endNumber [Step increment]

    One or more VB statements

Next [counter]

The brackets [ … ] are meta characters and indicate that the keywords in the square brackets are optional.

Page 57: INF110 Visual Basic Programming  AUBG Spring semester 2011

57

For index = 0 To n Step s

...

Next

Controlvariable

Startvalue

Stopvalue

Amountto add to

index

Page 58: INF110 Visual Basic Programming  AUBG Spring semester 2011

58

For … Next Loop Syntax

The most common use of the FOR loop omits Step increment – the default increment is +1, i.e. the counter is increased by 1 each time through the loop.

Page 59: INF110 Visual Basic Programming  AUBG Spring semester 2011

59

Sample

For i = 1 To 5

...

Next

The loop control variable (i.e. counter), i, is – Initialized to 1– Tested against the stop value, 5– Incremented by 1 at the Next statement

Page 60: INF110 Visual Basic Programming  AUBG Spring semester 2011

60

For i = 1 To 5 [Step 1] ...Next

And its corresponding Do While equivalent

i = 1

Do While i <= 5

...

i = i + 1

Loop

Page 61: INF110 Visual Basic Programming  AUBG Spring semester 2011

61

(a) For counter=1 to 10

Console.Writeline(counter)

Next

(b) For counter=1 to 100 Step 10

Console.Writeline(counter)

Next

(c) For counter=100 to 5 Step -5

Console.Writeline(counter)

Next

Examples

Page 62: INF110 Visual Basic Programming  AUBG Spring semester 2011

62

    For Num = 1 To 10        NumSquared = Num*Num        Console.Writeline(NumSquared)    Next Num

The statements between the "For Num = 1 To 10" line and the "Next Num" line are executed ten times.The first time, the variable Num contains the value 1.The second time, Num contains the value 2, the third time, 3, and so on.On the tenth time around (the tenth "iteration") num contains the value 10.After that there are no further iterations - the computer moves on to the line following the "Next num" line.

Page 63: INF110 Visual Basic Programming  AUBG Spring semester 2011

63

Start, Stop, and Step values

• Consider a loop beginning with

For i = m To n Step s

• The loop will be executed exactly once if m equals n no matter what value s has.

• The loop will not be executed at all if m is greater than n and s is positive.

• The loop will not be executed at all if m is less than n and s is negative.

Page 64: INF110 Visual Basic Programming  AUBG Spring semester 2011

64

Altering the Control Variable

• The value of the control variable should not be altered within the body of the loop• Doing so might cause the loop to repeat

indefinitely • Or have an unpredictable number of

repetitions.

• The value of the control variable should not be referenced after the Next statement

Page 65: INF110 Visual Basic Programming  AUBG Spring semester 2011

65

Altering the Control Variable

For I = 0 to 10

Console.WriteLine(i)

I = I – 1

Next I

This is a loop that never ends. Why?

Page 66: INF110 Visual Basic Programming  AUBG Spring semester 2011

66

Altering the Stop Value

The stop value may be specified as literal For I = 0 to 10

The stop value may be specified as constant Const MyConst As Integer = 10

For I = 0 to MyConst

The stop value may be specified as variable Dim endValue As Integer

endValue = 10

For I = 0 to endValue

Page 67: INF110 Visual Basic Programming  AUBG Spring semester 2011

67

Altering the Stop Value

Attention: keep in mind when working with For…Next loops that the stop value is set at the beginning of the loop. Changing the value of the EnDVariable in the loop’s body won’t have any effect.

For example, The following loop will execute 11 times, not 51

Dim endValue As Integer = 10

For I = 0 to endValue

endValue = 50

Console.WriteLine(endValue)

Next I

Page 68: INF110 Visual Basic Programming  AUBG Spring semester 2011

68

Non-integer Step Values

• Can lead to round-off errors with the result that the loop is not executed the intended number of times.

• The loop counter should be Integer.

Page 69: INF110 Visual Basic Programming  AUBG Spring semester 2011

69

Non-integer Step Example

• A loop beginning with

For i = 1 To 2 Step 0.1

will be executed only 10 times instead of the intended 11 times.

It should be replaced with

For i = 1 To 2.01 Step 0.1

Page 70: INF110 Visual Basic Programming  AUBG Spring semester 2011

70

Nested For … Next Loops

Page 71: INF110 Visual Basic Programming  AUBG Spring semester 2011

71

Questions?Questions?

Page 72: INF110 Visual Basic Programming  AUBG Spring semester 2011

72

Thank You For

Your Attention!