You are on page 1of 9

3/2/2024

SIT103 VISUAL PROGRAMMING DECISION MAKING


Lecture 6 & 7 STATEMENTS/STRUCTURES

MAKE AN INFORMED DECISION


(FANYA UAMUZI UNAOFAA) By Mbogo Njoroge

By Mbogo Njoroge

1
2

Decision Making Statements


The Flow of Program Control  Many times we want programs to make decisions such as;
 Is the lift overloaded or not ? Is its door obstructed ?, should the
• The order of statement execution in a program is referred to as lift gate/door close?, should the lift take off? , on which floor is it
the flow of program execution control
to stop? Should its door open?
• Unless specified otherwise, the order of statement execution
through a program or a function is linear: one statement after  What drink should we dispense from the vending machine? At
another from the first to the last. This is known as sequential what amount? What change if any should buyer get?
execution  Should we let the user withdraw money ATM and how much?
• Some programming statements allow us to: • Decision making structures require that the programmer specify
i. decide whether or not to execute a particular statement
one or more conditions to be evaluated or tested by the program,
ii. execute a statement over and over, repetitively
• These decisions are based on boolean expressions (or
along with statement(s) to be executed if the condition is
conditions) that evaluate to either true or false determined to be true, and optionally, other statement(s) to be
• A branching statement chooses between two or more executed if the condition is determined to be false.
possible actions.
DecisionSelection Statements Repetition/ Loop Statements
• A loop statement repeats an action until a stopping
condition occurs. •Using IF and IF...ELSE • While
•Nested IF Statements • Do Statements(Do while &
•Using SELECT Statement Do Until)
• For statements
3 4

The IF statement
Conditional Statements  The C++ syntax of the if statement is:
• A conditional statement lets us choose which statement If ( logicalCodnition) Then
will be executed next // Block of code to execute if expression is TRUE;
• Therefore they are sometimes called selection statements End If
• Conditional statements give us the power to make basic
decisions
• The VB conditional statements are the:
– If statement If
true
Condition
?
– If … Else statement
Block of code exc.
– If … ElseIf statement false

– Select statement

 When expression is true, the block of code is executed


 When expression is false, the block of code is skipped
5 6
3/2/2024

The if statement The IF statement program examples


 If the logical expression is true, we take one path through the
‘Program:- Using a Simple if statement
diagram (executing theaction/ block of code)
 If the logical expression is false, we take a different path through Private Sub frmSmallOfTwo_Click( )
the diagram (skipping over the action/block of code) Dim a As Single, b As Single
a = InputBox( “Enter the value of a “)
b = InputBox( “Enter the value of b “)

If (a < b) Then
if true if true
MessageBox.Show( “a = “ & a & “b = “ & b &
condition
condition
?
? VbCrLf “a is smaller than b” )
End If
Block of code
Block of code
exc.
false exc.
false End Sub

7 8

The If … Then … Else statement The If Then … Else statement logic


 Sometimes we need ONE of TWO mutually exclusive actions to be
executed. With one of the two being executed when a given condition  If the logical condition is true, take the path through block1 of
is TRUE and the other action executed when the condition is FALSE statements as shown in the diagram (executing one block1 of
 The VB syntax of the If … Then … Else statement is: code)

If ( logicalCondition) Then
T // Block1 of code to execute if condition is true;
false if true
Else
condition
F // Block2 of code to execute if condition is false;
?
End If

Block2 of stmts Block1 of stmts


executes executes

9
10

The If Then … Else statement program example


 If the logical condition is false, take the path through block2 of
statements as shown in diagram below(executing the block2 Private Sub frmTwoNumbers_Click( )
of code) Dim a As Single, b As Single
a = InputBox( “Enter the value of a “)
b = InputBox( “Enter the value of b “)

If ((a > 0) And (b > 0)) Then

false if true
condition MessageBox.Show(“Both a and b are positive” & VbCrLf &
T
“a - b = “ & (a – b) & VbCrLf &
? “ b - a = ” ( b – a) )
Else
Block2 of Block1 of
stmts MessageBox.Show(“Either or both a and b are < = zero:”;
stmts
executes & VbCrLf & “a + b = ” & (a + b) & VbCrLf
executes F “b x a = ” & ( b * a ) )

End If
MessageBox.Show(“Hongera kwa ujuzi wako wa HESABU”)
End Sub

11 12
3/2/2024

Concatenated If … Then … ElseIf Statement


The logical flow of the concatenated/ladder
In VB the concatenated/ ladder If … Then … ElseIf is used when we have to
If … Then … ElseIf statement
execute one of several mutually exclusive actions. In other words only one
of the several possible actions has to be selected
Syntax:
If (condition1) Then If
condition1
Block1 of stmts to exc if condition1 is TRUE;
?

ElseIf (condition2) Then


Block2 of stmts to exc if condition2 is the 1st to
If
evaluate to TRUE; condition2
Block1 of ?
ElseIf (condition3) Then stmnts exc.
Block3 of stmts to exc if condition3 is the 1st to
evaluate to TRUE; If
conditionR
Block2 of ?
stmnts exc.

ElseIf (conditionR) Then


BlockR of stmts to exc if conditionR is the 1st to BlockR of Block(R+1) of
evaluate to TRUE; stmnts exc. stmnts exc.
Else
Block(R+1) of stmts to exc if ALL ondition 1 to R
above are FALSE; 13 14
End If

Select Case - syntax


The Select Case Statement • The general syntax/layout of a Select statement is:
Select( Match_expression )
Case value1
statement-list1
• Select is a VB conditional statement, that tests a
variable/expression for equality against a set of values. Case value2
Each value in a Case clause is referred to as a Case statement-list2
episode Case value3
• The Select Case control structure is slightly different from . statement-list3
the If....ElseIf control structure . The advantage of the . .
Select Case statement over multiple If. . .Then. . .ElseIf . .

statements is that it makes the code easier to read and . .


Case valueN
maintain. statement-listN
• The Select Case structure evaluates a single expression at
Case Else
the top of the structure. The result of the expression is statement-list to execute if none of the
then compared with several values; if it matches one of values 1 to N above that equals expression
them, the corresponding block of statements is executed.
End Select
===xxx====

15 16

Select Case Logical Flow The Select Statement Explanation


• The matchExpression can be any variable
select ( matchExpression )
Set Match Expression to or expression, but usually a variable.
Case value1
some value • The Case clause value? can be
statement-list1
a value Case 1
a list of values Case “red”, “yellow”
Case value1
True
Block1 of stmts exc. Break;
Case value2 a range of values Case 1 to 10
? statement-list2 a comparison Case Is > 5
a combination Case 1, 4 to 8, is > 12
False Case value3 • The matchExpression and values? should
True
. statement-list3 be of the SAME data type.
.
Case value2 Block2 of stmts exc. Break; • Each case clause is tested for a match (or
?
. mismatch) in the order they appear. AND
. . as soon as a case value match the
False
. matchExpression the statements
associated with that case clause are
.
.
.
. executed and control passes to the
. Case valueN statement following the End Select.
. . statement-listN • If matchExpression matches a value in
more than one Case clause, only the
Case Else statements following the first match are
Case valueN True
BlockN of stmts exc. Break; statement-list to execute executed.
? if none of the values 1 to N • The Case Else statement is optional. If
above that equals expression none of the Values 1 to N satisfy the
False
End Select matchExpression the statements
Block(N+1) of stmts exc. ===xxx==== associated with the Case Else clause are
default action(s) executed.

17 18
3/2/2024

Select Statement Rules VB DECISION MAKING LOOP


i. The value1, ... upto valueN must have the same data type as the STATEMENTS/STRUCTURES
value of the switch-expression. The resulting statements in the case
statement are executed when the value in the case statement matches
the value of the matchExpression. (The case statements are executed
in sequential order.)
ii. The Case Else clause, which is optional, can be used to perform
actions when none of the specified Case clause values is true.
iii. The order of the Case clause (including the Case Else clause) does
not matter. However, it is a good programming style to follow the
logical sequence of the cases and place the Case Else clause at the
end.
iv. If there is no Case Else (default) clause, and no Case clause value
matches/equal to matchExpression, control falls through to the
statement after the body of the Select statement
v. Any number of Case clauses can be included in the body of a Select
Case statement.
vi. The Select statement can be nested(a Select statement within another
Select statement)
• You can use multiple expressions or ranges in each Case clause. Eg;
Case 1 To 4, 7 To 9, 11, 13, Is > maxNumber
19 20

Repetition/Loop Statements
Most Common Uses of Loop Statements
• Repetition statements allow us to execute a statement or a block
of statements multiple times
• Iteration or looping refers to the specified sequence in which a • The repetitive/loop statements are used for one or
pattern or a block of code is repeated until the condition becomes some of the following tasks:
no longer true. That is, as long as the condition remains true, the
loop is executed repeatedly. The repetitive cycle is terminated – counting
when the condition becomes false.
– accumulating, i.g. summing
• VB has three kinds of repetition statements:
– searching
i. While … Wend
– sorting
ii. Do … Loop (in two variations/flavours While and Until)
iii. For … Next – displaying tables
• Basic Components of Loop structures are; – data entry – from files and users
– Loop control variable: A variable used to determine whether a loop – menu processing
will be executed – list processing
– Loop body: The statement (s) that are executed each time a loop
repeats
• The programmer should choose the right kind of loop statement
for a particular situation
21 22

Entry-controlled v/s Exit-controlled loops


THE While LOOP STATEMENT
• Entry-controlled (a.k.a. pre-condition) loops
Before executing the loop, the given condition is checked
beforehand and therefore the minimum number of times possible • It is an entry controlled statement(Why?)
for the action to execute is ZERO
• If the loop body gets executed, the flow of control
goes back to the beginning of the loop again,
Examples of these loops in VB are the While … Wend, the
For … Next, and the pre-condition Do While … Loop and the checking if the condition still hold true or not. If
Do Until … Loop statements. true the loop body is executed again and again until
the condition evaluates to false
• Exit-controlled (a.k.a. post-condition) loops
The body of the loop statement is executed before the repeat-
condition testing. As such this type of loops offers the benefit to • After loop termination, the flow of control is
execute the loop at least ONCE. In this case, to execute the loop directed to the statement immediately after the
body for the first time, the test condition need not necessarily be Wend key word
true.
Examples of these loops in VB is the Do … while Loop and the
Do … Until Loop statements

23 24
3/2/2024

Example demonstrating use of a While loop


Syntax and Flowchart representation of the While Private Sub numPawor_Click( )
statement ListBox1.Items.Clear()
ListBox2.Items.Clear()
Dim i As Integer = 1 OUTPUT
While(condition) lstNum.Items.Add(“Number”) Number Its Square
statements to execute if the condition is TRUE lstNumPow.Items.Add(“Its Square”) 1 1
End While While (i <= 6) 2 4
……. lstNum.Items.Add(i) 3 9
lstNumPow.Items.Add(i ^ 2) 4 16
i=i+1 5 25
End While
End Sub 6 36

• This while loop will execute the block of code 6 times


• The loop index variable namba values will go from 1,2,3,4,5,6,7
• When namba equals 7 the loop body will not executed again
T AND the program execution control will be transferred to the
While condition Block of stmnts
executes statement immediately below the while statement(ie End Sub)
?

Assignment TASK
F Draw a complete flowchart to depict the logic of the above event procedure
Amend the event procedure code so as to display the SUM of numbers and the SUM of the squires as
the last items in the two list boxes respectively designated as; TOTAL = ?_
25 26

The Do … Loop Statements


• There are two variations of the Do . . . Loop statement; both
• There are two variations of the Do. . .Loop statement; both use the use the same basic model. A loop can be executed either while
same basic model. A loop can be executed either while the condition is the condition is True OR until the condition becomes True.
True or until the condition becomes True. These two variations use the
These two variations use the keywords While and Until to
keywords While and Until to specify for how long the statements will
be executed. specify circumstances under which the statements will be
• The expression is evaluated either at the beginning of the loop (before executed.
executing any statements) or at the end of the loop (the block • The Do … Loop statement may be implemented in one of two
statements are executed at least once). different variations/flavors; the While and the Until flavors/forms
• To execute a block of statements while a condition is True, use the
• Each of these two variations of the Do … Loop may also be
following syntax:
implemented either as pre-condition or post-condition mode
Do While condition
statement-block • In pre-condition mode expression is evaluated either at the
Loop beginning of the loop (before executing any statements)
• To execute a block of statements until the condition becomes True, use • In pst-condition mode the condition at the end of the loop (the
the following syntax: block statements are executed at least once).
Do Until condition
statement-block While Pre-condition mode
Loop Do
Until Post-condition mode
27 28

Similarities & differences between pre-condition Logical Similarities & differences between pre-condition
Do While … Loop and pre-condition Do Until … Loop Do While … Loop and pre-condition Do Until … Loop
Do While … Loop Do Until … Loop Do While … Loop Do Until … Loop
Syntax: Syntax: The loop Semantics Pseudcode The loop Semantics Pseudcode
Do While(condition) Do Until(condition)
statements to execute statements to execute 1.Test the condition 1.Test the condition
repeatedly as long as the repeatedly as long as the
condition remains TRUE condition remains FALSE 2. If condition is TRUE execute action 2. If condition is FALSE execute action
Loop Loop 3. Repeat step 1 process 3. Repeat step 1 process

Logical Flow: Logical Flow: Logical Flow: Logical Flow:

29 30
3/2/2024

Similarities & differences between post-condition


Comparison
Do … Loop While and post-condition Do … Loop Until
pre-condition Do While … Loop and pre-condition
Do Until … Loop Do … Loop While Do … Loop Until
Syntax: Syntax:
The Comparison Do Do
Do While … Loop Do Until … Loop statements to execute once ; statements to execute once ;
Pre-condition/Entry-controlled Pre-condition/Entry-controlled AND then repeatedly as long as AND then repeatedly as long as
loop(The looping condition is tested loop(The looping condition is tested
the condition remains TRUE the condition remains FALSE
at the top before executing the loop at the top before executing the loop
Similarities

body) body) Loop While(condition) Loop Until(condition)


Minimum No. of times possible for Minimum No. of times possible for
iteration action is ZERO iteration action is ZERO
(When does this happen/occur ?) (When does this happen/occur ?) Logical Flow: Logical Flow:
Loops/iterates as long as the Loops/iterates as long as the
condition is true condition is false
Differences

Uses the keyword While Uses the keyword Until

NB:- The main logical operational difference between these two is that the
Do While … Loop statement iterates as long as the condition is true and the
Do Until … Loop statement iterates as long as the condition is false
31 32

Logical Similarities & differences between pre-condition


Do While … Loop and pre-condition Do Until … Loop Comparison
post-condition Do … Loop While and post-condition
Do While … Loop Do Until … Loop Do … Loop Until
The loop Semantics Pseudcode The loop Semantics Pseudcode
1. Execute Action 1. Execute Action The Comparison
Do … Loop While Do … Loop Until
2. Test the condition 2. Test the condition Post-condition/Exit-controlled Post-condition/Exit-controlled
If condition is TRUE If condition is FALSE loop(The looping condition is tested loop(The looping condition is tested
Then execute the Action at the bottom after executing the at the bottom after executing the
Similarities

Then execute the Action


3. Repeat step 2 process loop body) loop body)
3. Repeat step 2 process
Minimum No. of times possible for Minimum No. of times possible for
iteration action is ONCE iteration action is ONCE
Logical Flow: Logical Flow: (When does this happen/occur ?) (When does this happen/occur ?)
Loops/iterates as long as the Loops/iterates as long as the
condition is true condition is false
Differences

Uses the keyword While Uses the keyword Until

NB:- The main logical operational difference between these two is that the
Do … Loop While statement iterates as long as the condition is true and the
Do … Loop Until statement iterates as long as the condition is false
33 34

Jua na Ukumbuke: Example demonstrating use of a do … Loop while statement

• Both the post-condition Do … LOOP While and Do … LOOP This do while loop will prompt the user
Private Sub frmShowNum_Click( ) for a numeric data item one or more
Until are exit-controlled loop(why?). times until a time he/she enters a
Dim numYako As Single NEGATIVE number for the iterations to
• Both gives the user the provision to execute the loop action at least
Dim numSum As Single stop
once, which is useful for checking user input among other things
numSum = 0 Note the Exit Do statement , ina
umuhimu upi?(What is its purpose?)
numYako = 0
• In both;
First, the body of the loop is executed, then the condition is tested Do
for truth or falsity numYako = InputBox("Enter +ve No. to CONTINUE or –ve No. to STOP “)
• In theory and infact the loop body can be either a single statement If (numYako < 0) Then
or a block of statements Exit Do
End If
• If the execution of the body statements of a Do Loop strictly numYako = numSum + numYako
depends on the condition, you should use either the pre-condition Loop While (numYako >= 0)
Do While … Loop OR the pre-condition Do Until … Loop
However, if the body statements of a Do Loop must be executed at MessageBox.Show(“ The sum of your numbers is: “ & numSum)
least once or if it is inconsequential whether the condition is End Sub
checked before entering the loop, Then use either post-condition
Do … Loop While OR the post-condition Do … Loop Until
35 36
3/2/2024

Sample screen-shots of the On-Form output and Assignment Task – Loops 1A


corresponding dialog boxes for the input data items
40, 80, 60.8, and -3 respectively Question 1
a) Type the above program, compile, debug and execute in a VB
environment. Run the program at least 3 times with different
input data items and capture the output result for 3 times, paste
in MS Word document in readiness to submit
-3
b) In the same MS Word document draw a COMPLETE flowchart to
depict the operational logic of the program
Question 2
a) Modify your Q1 program to perform the same task though an
implementation of ;
i. a While … Wend statement Copy the code of each of
ii. a Do While … Loop statement these programs and
iii. a Do Until… Loop statement paste in the same MS
iv. a Do … Loop Until statement Word document as Q1

b) In the same MS Word document draw a COMPLETE flowchart to


Assignment TASK
depict the operational logic of each of your Q2(a) program
Draw a complete flowchart to depict the logic of the above event procedure
Dry-run your flowchart and trace the output sequence and results
37 38

Infinite Loops
• The Endless Loop
• Notice that in the previous structures, some of the statements
• In a Do … Loop statement the While/Until
inside the loop must produce some result clauses and their associated condition are
• that causes the condition to be False in co optional; that is, the entire Do structure
• njunction with the keyword While, or True in conjunction with
can do without any While/Until condition.
• the keyword Until; otherwise, the loop will execute endlessly,
resulting in an undesirable trap. Eg, it is perfectly legitimate to have a
• Thoroughly test your program to prevent this situation from Do...Loop structure as follows:
happening.
Do
• A loop must have some way to end itself ‘Statements to be executed
• Something within the body of the loop must eventually force
the test expression to false
Loop
• In the previous example
– The loop continues to repeat
– intCount increases by one for each repetition
– Finally (intCount <= 10) is false and the loop ends
• If the test expression can never be false, the loop will
continue to repeat forever
– This is called an infinite loop 39 40

The For … Next repetitive statement The For … Next statement operational Logic
The general syntax/format of the For … Next loop and its • A For … Next loop is counter-controlled, meaning that it is normally
corresponding flowchart are shown below used whenever the number of iterations is known in advance.
For counter = startingValue To terminalValue Step incrementValue • Within the header of the For loop the loop counter initialization,
terminal value condition, and counter increment are specified
statements to execute repeatedly as long as the terminal
condition remains TRUE
• Note that For, To, Step, and are keywords
Next counter • The loop counter increment value associated with the Step clause can
be either a positive or a negative value; if the Step clause is omitted,
automatically 1 is by default qualified as the increment value.

Initialize • The operational Logical Steps are as follows;


counter variable 1. The initialization step occurs one time only, before the loop
begins.
2. The terminal condition is tested at the beginning of each iteration
of the loop.
• If the terminal condition is true, then the body of the loop is
For executed.
terminal T Block of Increment
statements loop counter • If the terminal condition is false, then the body of the loop is
condition
executes variable not executed, and execution is transferred to the statement
? immediately below the loop.
F 3. The incrementing of the loop counter index takes place , then
41 42
repeat step 2 process
3/2/2024

Example: Using a FOR loop to Add consecutive


integers from 1 to a specified +ve endpoint integer Example: Using a FOR loop to capture input details of
goats bought by a farmer
Private Sub btnAddNumz_Click( )
lstBoxNumz.Items.Clear( ) Private Sub cmdGoatRecord_Click( )
Dim numzSum As Integer = 0 Dim i As Integer, mbuziNgapi As Integer, mbuziType As String
Dim numStop As Integer Dim mbuziCost As Currency , totoCost As Currency
numStop = InputBox(“Enter your endpoint +ve integer”) totoCost = 0
mbuziNgapi = Val( InputBox(“How many goats dd’u buy?”))
For i As Integer = 1 To numStop Step 1 For i = 1 To mbuziNgapi Step 1
numzSum = numzSum + i lstGoats.Items.Add( “Mbuzi ” & i)
lstBoxNumz.Items.Add(i) mbuziType = InputBox(“Is Goat No. “ & i & “ (M/F)?”)
Next mbuziCost = Val( InputBox(“Enter buying price of Goat “ & i))
lstBoxNumz.Items.Add("Their Sum is: " & numzSum) lstGoatCost.Items.Add( mbuziType & “ Ksh. “ & mbuziCost )
End Sub totoCost = totoCost + mbuziCost
Next i
**Exercise: MessageBox.Show( “THE TOTAL COST OF U’R GOATS IS KSH. “ & totoCost)
Modify the above program to Add consecutive integers from specified positive start-
point to a specified positive endpoint(Eg. To add all integers from 12 to 26) End Sub
43 44

Run-time Program Screens and Dialogs


3
Enforcing an Early/Prematurely Quit in a Loop

• In practical real operational situations, episodes do arise that makes


it is desirable to end a loops iterations before its terminal condition
is satisfied/fulfilled
2
4 • In VB 6, the Exit statement is used as a typical unconditional jump
statement and is useful to enforce early/prematurely Quit from
within For , Do loops and While loops and transfers the program
execution control to the statement immediately following the loop
1 body.
SEQUENCE OF SCREENS AND DIALOGS • The following statements accomplish this
1. Start by clicking the “Show Goats Cost” button at – Exit Do (used in Do While or Until loops)
RUN-TIME
2. Specify the No. of goats (4 in this case) – Click OK – Exit For (used in For Next loops)
3. Specify whether goat is Male or Female (M in this
case) - Click OK
4. Specify the buying price of the goat (5000 in this
case) - Click OK • If enforced in an inner nested loop the Exit statement terminate
the execution of that inner loop and transfers the execution to its
F Continue thru repeated cycle of STEP 3 and 4 for
the remaining goats immediate outer loop
F. Eventually you get the FINAL results screen as
shown to the immediate left
**Exercise:
Modify your GUI design to incorporate the GOAT FARM red title in a label control and the
46
goats picture in a picture box and output results layout as shown in display Window F above 45

A Closer Look at the Loop Index Increment value For ... Next loop with positive and negative
loop counter/index increment value
Kumbuka:- the loop counter/index increment value can be either
positive or negative.

• If the increment value is positive, the loop will end as soon as


the counter gets greater than the terminal value. If the
starting value is greater than the ending value, the loop will counterVariable
counterVariable

terminate immediately and the statements inside the loop >


<
terminalValue
terminalValue
body will never be executed.
No

• If the increment value is negative, the loop will end as soon as


the counter gets less than the terminal value. In this case, if
the starting value is less than the ending value, statements
inside the loop body will never be executed.

• The flowchart fragments in the next slide demonstrates the


logic of how the For...Next loop works with positive and
negative loop counter/index increment value.
NB:- when the increment is negative, adding it to the counter will
decrease the value of the counter/index variable.
47 48
3/2/2024

Run-time Program Screens and Dialogs


Example: Using the Exit Command/statement
Private Sub Command1_Click()
2
Cls
Dim i As Integer, bagNgapi As Integer, moSpace As String
bagNgapi = InputBox("How many bags d’u need?")

MessageBox.Show( "Your Oder is “ & bagNgapi & " Bags" 3

For i = 1 To bagNgapi Step 1 R


If (i > 6) Then
moSpace = InputBox( i - 1 & " Bags delivered; Is there some more Space?(Y/N)")
If (moSpace = "N") Then SEQUENCE OF SCREENS AND DIALOGS
MessageBox.Show ("Sorry, You ordered" & bagNgapi & " bags" & 1. Start by clicking the “Bags Delivery
Order” button at RUN-TIME
vbCrLf & “ Nimeleta " & (i – 1) & vbCrLf & "Lakini Space Imeisha") 2. Specify the No. of bags (10 in this case)
Exit For – Click OK
3. Specify whether there more space Y/N
End If (N in this case) - Click OK
End If
Next i Continue thru repeated cycle of STEP 2
and 3 in case your response in 3 is Y
MessageBox.Show ("THANK YOU FOR TRUSTING US") F
End Sub R. You get the final comprehensive
RESULTS screen and dialog - Click OK
50

49
F. Eventually the FINAL appreciation
screen pops up

Which Loop do I use AND under which under Controlling the Loop Iterations
circumstances
• If number of time action is to be repeatedly executed is NOT known • Sentinel Value
AND there is a possibility of the action not being executed at all, with – For all loop statement/structure type, the loop continuation
NO possibility of enforcing an early/premature EXIT use the While … condition usually determine when to end the loop by making some
Wend loop. comparison to a Sentinel value
• If number of time action is to be repeatedly executed is NOT known – The sentinel value serves as the test value or comparison criteria for
AND there is a possibility of the action not being executed at all, BUT ending the loop
with a possibility of enforcing an early/premature EXIT then use the
• In counted loops this is usually the number of times to loop
pre-condition Do … Loop While or the Do … Loop Until statement.
• In event controlled loops this is the state or value that the event
• If it is important that the action MUST be executed at least ONCE, with variable is compared to in the test expression
a possibility of enforcing an early/premature EXIT, then use either the
post-condition Do … Loop While or the post-condition Do … Loop • Loop Counter /index
Until statement – A numeric variable that keeps track of or counts the number of
• If it is necessary that the action MUST be executed at least ONCE, with iterations a loop repeats, items that have been processed, or some
a possibility of enforcing an early/premature EXIT, then use either the other repeated occurrence within a loop
post-condition Do … Loop While or the post-condition Do … Loop
Until statement • Accumulator
• If you know ( or can calculate ) the number of times an action is to be – A numeric variable that is used to hold a sub-total that is computed
repeatedly executed, with a possibility of enforcing an during multiple passes/iterations through a loop
early/premature EXIT then use the counter-controlled For … Next
loop. 51 52

When to use Counter-controlled loop & When to use


Event-controlled loop
• Counter-controlled loops
– repeat a specific number of times
– Counters are typically initialized before the loop begins
– The counter is then modified in the body of the loop

• Event-controlled loops
– repeat until something happens within the loop body to change
the value of loop control variable
– Events can be: User Input, Expression results, Function results,
etc.

53

You might also like