0% found this document useful (0 votes)
8 views

COSC226 Module4

Uploaded by

Quincy Nouah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

COSC226 Module4

Uploaded by

Quincy Nouah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Visual Basic.

NET

COSC 226
TOPIC: Control Structures in Visual Basic .NET
Outline:

 Selection Control Structures


 If-Then Statement
 If-Then Else Statement
 If-Then ElseIf Statement
 Select Case Statement

 Iteration Control Structures


 While End
 Do While
 Do Until
 For… Next
Introduction:
 Control structures specify the order in which tasks are execution.
 There three main control structures:
 Sequence
 Selection(Decision/Conditional Structure)
 Iteration(Loop or Repetition)
 Sequence: statements are executed one after another – the default
 Selection: statements executed base on condition
 Iteration: statements executed a number of time

Note:
The rationales for using both selection and iteration control statements and their
functions remain the same with the previous programming languages you have
learned.
It’s only the syntax that differs.
So, we shall go through the syntax, examples and exercises.
Selection Control structures:
• Selection control statements are the statements that controls the
execution of the program on the basis of the specified condition.
• It is useful for determining whether a condition is true or not.
• VB.NET provides the following conditional or decision-making
statements.
• If-Then Statement
• If-Then Else Statement
• If-Then ElseIf Statement
• Select Case Statement
Selection Control structures: If-Then Statement
• Syntax • Example
If condition Then Module Module1
Sub Main()
[Statement or block of Dim monthNum As Integer
Statement]
Console.Writeline(“Enter a number of a month:”)
End If monthNum = Console.Readline()
If monthNum = 12 Then
Console.WriteLine("Welcome to Christmas
• This statement executes the Period")
statements depending upon the End If
given condition. Console.ReadKey()
• If the condition is evaluated to be End Sub
true it execute the statement(s), End Module
and exit.
Selection Control structures: If-Then Statement

• Class Exercise

Create an if statement that will check if the variable salesAmt is greater


than the constant SALES_QUOTA. If true, create a block statement that
will calculate salesAmt * BONUS_PERCENT and store the result in a
variable named bonusPay. The block statement will then compute
totalPay by adding salesAmt to bonusPay. Outside of the if structure,
add a Writetline statement that will output the totalPay value.
Selection Control structures: If-Then Else Statement
• Syntax • Example
If (condition) Then 1. Module Module1
2. Sub Main()
statements1 3. Dim num As Integer
Else 4. Console.WriteLine("Enter the Number")
5. num = Console.ReadLine()
statements2
6. If (num Mod 2 = 0) Then
End If 7. Console.WriteLine("It is an even number")
• If the condition is True, the code 8. Else
executes the statement1. If the 9. Console.WriteLine("It is an odd number")
condition is False, the code 10. End If
executes the statement 2 11. Console.ReadKey()
12. End Sub
13. End Module
Selection Control structures: • Example: Write a Console based VB.Net application to calculate the
average score of a student in 5 courses and allocate a grade to the average
If-Then ElseIf Statement score using Babcock grading system.
Module Module1
• Syntax Sub Main()
If condition1 Then Dim s1, s2, s3, s4, s5, avg As Integer
Console.WriteLine("Enter marks in five subjects ")
statements1 ... s1 = Console.ReadLine()
ElseIf condition2 Then s2 = Console.ReadLine()
s3 = Console.ReadLine()
statements2 ... s4 = Console.ReadLine()
ElseIf condition3 Then s5 = Console.ReadLine()
avg= (s1 + s2 + s3 + s4 + s5) / 5
Statement3.. If (avg >= 80) Then
. Console.WriteLine(" Average grade is A")
ElseIf (avg >= 60) Then
.
Console.WriteLine(" Average grade is B")
Else ElseIf (avg >= 50) Then
Console.WriteLine(" Average grade is C")
default statements ...
ElseIf (avg >= 45) Then
End If Console.WriteLine(" Average grade is D")
• It provides an opportunity to execute only one ElseIf (avg >= 40) Then
statement or block of statements from multiple choices. Console.WriteLine(" Average grade is E")
Else
• Execution starts from the top to bottom, and it checked Console.WriteLine(" Average grade is F")
for each If condition. And if the condition is met, the End If
block of If the statement is executed. And if none of the
End Sub
conditions are true, the last block is executed.
End Module
Selection Control structures: If-Then ElseIf
Statement
• Class Exercise

Given the following tax table information, write VB.NET program to print the taxRate appropriate to a particular
pay.
If pay is more than 100,000, tax rate is 40%
If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30%
If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20%
If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10%
If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5%
If pay is less than or equal to 5,000, tax rate is 0%
Selection Control structures: Nested If

• If statement written inside another If statement


• The syntax is:
If condition Then
If Condition Then
Statement(s)
End If
End If
CONTROL STRUCTURES
(Flow of Control)
• Control structures specify the order in which tasks are execution .
• There three main control structures:
• Sequence
• Selection(Decision Structure)
• Iteration(Loop or Repetition)
• Sequence: statements are executed one after another – the default
• Selection: statement is executed base on condition
• Iteration: statements executed a number of time
Selection cont.
• Selection Statements is classify into two types
• Single selection(one-way)
• Dual selection(two-way)
• One-way selection statement:
• Evaluates logical expression
• Executes statements only if expression is true
• Two-way selection statement:
• Evaluates logical expression
• Executes statements if it is true
• Executes different statements if it is false
Selection cont.
• Single (One-way) Selection flowchart
Selection
• Make decisions in selection statement by writing logical expressions
• Logical expression evaluates to true or false
• Use to compare two values

• Relational operator
• Use to make comparison in logical expression
Selection cont.
• The selection statement use in VB.NET include:
• If Then statement
• If Then Else statement
• Select Case statement
Selection cont.
• Writing one-way Selection statements
• Single-line If syntax:
If (condition) Then statement

• Multi-line If syntax:
If ( condition) Then
statement
.
statement
End If
Selection cont.
• Multi-line if:

• Statements written on separate lines

• Keyword End If must be used to terminate If statement


Selection cont.
• Example of Single-line If statement flowchart
Selection cont.
• Dual(Two-way) selection statement flowchart
Selection cont.
• Writing dual(two-way) selection statements
• Syntax:
If (condition) Then
statement(s)
Else
statement(s)
End If
• ElseIf
• Combines Else and If
Decisions and Conditions

• The If/Then structure is called a single-selection


structure because it selects or ignores a single action (or a
sequence of actions).
• The If/Then/Else structure is called a double-selection
structure because it selects between two different actions
(or sequences of actions).
• If statements: a decision made by the computer is formed
as a question. Is a given condition True/False. If it is true do
one thing, if it is false, do something else.
• If the sun is shining then
• Go to the beach
• Else go to class
• End if.
• For example, suppose that the passing grade on an
examination is 60 (out of 100). Then the
pseudocode statement
• If student’s grade is greater than or equal to 60 Print
“Passed”
• If studentGrade >= 60 Then
• Console.WriteLine("Passed")
• End If
Selection cont.
• Writing dual(two-way) selection statements
• When you want to execute one or more statements if logical expression is
true
• But also want to execute one or more different statements if it is false

• Nested If
• If statement written inside another If statement
• Can replace compound expression with nested If
If/Then/Else Selection Structure

• If student’s grade is greater than or equal to 60


• Print “Passed”
• Else
• Print “Failed”
• The preceding pseudocode If/Else structure may be written
in Visual Basic as

• If studentGrade >= 60 Then


• Console.WriteLine("Passed")
• Else
• Console.WriteLine("Failed")
• End If
If student’s grade is greater than or equal to 90
Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”
Most Visual Basic programmers prefer to write the
preceding If/Then/Else structure
• using the ElseIf keyword as
• If grade >= 90 Then
• Console.WriteLine("A")
• ElseIf grade >= 80 Then
• Console.WriteLine("B")
• ElseIf grade >= 70 Then
• Console.WriteLine("C")
• ElseIf grade >= 60 Then
• Console.WriteLine("D")
• Else
• Console.WriteLine("F")
• End If
• Module Module1
• Sub Main()
• Dim intInput As Integer
• System.Console.WriteLine("Enter an integer…")
• intInput = Val(System.Console.ReadLine())
• If intInput = 1 Then
• System.Console.WriteLine("Thank you.")
• System.Console.ReadLine()
• ElseIf intInput = 2 Then
• System.Console.WriteLine("That's fine.")
• System.Console.ReadLine()
• ElseIf intInput = 3 Then
• System.Console.WriteLine("Too big.")
• System.Console.ReadLine()
• Else
• System.Console.WriteLine("Not a number I know.")
• System.Console.ReadLine()

Examples
• If then statement
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• If /Then/ End If
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• Print “ Authorities have been notified”
• End If
• If/ Then/ Else/ End If
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• Print “ Authorities have been notified”
• Else
• Balance = Balance- Check
• End If
• To form conditions, six relational operators are used
to compare values. The result of the comparison is
either True/ False. It includes >,<, =,<>, >=, <=.
• Examples: intCountOne=5, intCountTwo=5,
intCountThree=-5 txtFour.Text= “Bit”, txtFive.Text
=“Byte”. Determine which conditions will evaluate
True and which ones will evaluate False
• intCountOne = intCountTwo T
• IntCountThree<0 T
• intCountThree< intCountTwo T
• intCountOne <> intCountTwo F
• intCountOne + 2 > intCountTwo+2 F
• txtFour.Text < txtFive.Text T
• “2”<> “Two” T
• “$” <=“?” T
Difference between Division and
Modulus
• If intTotalMinutes = 150
• Then
• intHours = intTotalMinutes\60
• i.e it returns 2 for intHours
• intMinutes = intTotalMinutes mod 60
• i.e it returns 30 for intMinutes
Assume that intFrogs=10, intToads=5 intPolliwogs=6.
what will be displayed for each of the following
statements.
If intFrogs> intPolliwogs then
radFrogs.checked= True
radToads.checked= false
Else
radFrogs .checked=false
radToads.checked= true
End If
• Ans: radFrogs will be checked
• radToads will be unchecked
(2) If intfrogs >intToads+ intPolliwogs then
lblResult.Text=“It’s the frog”
Else
lblResult.Text=“It’s the toads and the polliwogs”
end if
• Ans: It’s the toads and the polliwogs”
• (3) If intPolliwogs > intToads and intfrog< >0 then
• lblResult.Text= “It’s True”
• Else
• lblResult.Text= “It’s false”
• End if
• Ans: It’s True
(4) Write the statements necessary to compare the
numbers in txtApples.Text and txtOranges.Text. Display
in lblMost.Text which has more the oranges or the
apples.
Ans: if Cint(txtOranges.Text)> Cint(txtApples.Text) then
lblMost.Text = “Oranges”
else
lblMost.Text = “Apples”
end if
• Write the Basic statements that will test the current
value of decBalance. When decBalance is greater than
zero, the checkbox for funds available called chkFunds
should be selected, the decBalance set back to zero
and intCounter incremented by one. When
decBalance is zero or less, chkFunds should not be
selected (do not change the value of decBalance or
increment the counter)
• If decBalance> 0 then
• chkFunds.Checked = True
• decBalance=0
• intCounter+=1
• Else
• chkFunds.checked= False
• End If.
Exercise
• Write a program using If statement to take appropriate action if you
have asked a girl for a date.
• Given the following tax table information, write VB.NET program to
assgn the double TaxRate appropriately given the double pay. Use a
nested if- else statement. If pay is more than 100,000, tax rate is 40%.
• If pay is more than 60,000 and less than or equal to 100,000 tax rate is
30%. If pay is more than 30,000 and less than or equal to 60,000 tax
rate is 20%. If pay is more than 15,000 and less than or equal to
30,000 tax rate is 10%. If pay is more than 5,000 and less than or
equal to 15,000 tax rate is 5%. If pay is less than or equal to 5,000 tax
rate is 0%.
• Let’s say you deposit $1000 in a bank and the bank is paying you 5% compound interest annually.
• After the first year, you will earn an interest of $1000×0.05=$50. The new principal will be $1000+
$1000×0.05=$1000(1+0.05)=$1000(1.05)=$1050. After the second year, the new principal is
$1000(1.05)x1.05=$1000(1.05)2 =$1102.50. This new principal is called the future value.
• Following the above calculation, the future value after n years will be:
• FV = PV * (1 + i / 100)n
• Where:
• FV = Future Value
• PV =Present Value
• i = Interest rate
• n = time/duration (year/month).
• Therefore, implement the above calculation using a visual basic code. See figure below;
• Public Class Form1
• Private Function FV(pv As Single, i As Single, n As Integer) As Double
• FV = pv * (1 + i / 100) ^ n
• End Function

• Sub BtnCal_Click() Handles BtnCal.Click
• Dim FutureVal As Single
• Dim PresentVal As Single
• Dim interest As Single
• Dim period As Integer
• PresentVal = TxtPV.Text
• interest = TxtInt.Text
• period = TxtN.Text
• FutureVal = FV(PresentVal, interest, period)
• LblFV.Text = Forma(FutureVal, "$#,##0.00")
• End Sub
• End Class
Selection cont.
• Multi-way Selection statements
• Acts like multi-way If statement By transferring control to one or more
statements, depending on value of a variable
• Sometimes called case structure
• Uses keywords:
• Select
• Case
Select Case
• The Select Case structure is called a multiple-selection structure
because it selects among many different actions or sequences of
actions.
• Select Case statement chooses a block of statements to execute based
on some value e.g
• Select Case strColor
• Case “red”
• `-----------
• Case “Blue”
• `-------------
• Case “yellow”
• `----------
• Case Else
• `----------
• End Select
• If none of the case clauses matches the value in the
select case statement, the statements in the CaseElse
clause are executed. If more than one case clause
matches the given value, only the statements in the
first matching case clause executed.
Selection cont.
• Select Case Statement
• In some programming applications, different operations can occur based
upon the value in a single field
Syntax:
Select Case test_value
Case comparison_expression1
statements1
Case comparison_expression2
statements2
Case comparison_expression3
statements3
...
Case Else
else_statements
End Select
Selection cont.
• Using Ranges in Select Case Statements
• Example:
• Select Case gradeLevel
• Case 1 To 3
• writeline(“Junior “)
• Case 4 to 6
• writeline(“Middle”)
• Case 7 To 8
• Writeline(“High”)
• Case Else
• Writeline(“Invalid grade level”)
• End Select
• Module Module1
• Sub Main()
• Dim intstudentGrade As Integer
• System.Console.WriteLine("Enter an score…")
• intstudentGrade = Val(System.Console.ReadLine())
• Select intstudentGrade
• Case 90 To 100
• Console.WriteLIne("A")
• Console.ReadLine()
• Case 80 To 89
• Console.WriteLIne("B")
• Console.ReadLine()
• Case 70 To 79
• Console.WriteLIne("C")
• Console.ReadLine()
• Case 60 To 69
• Console.WriteLIne("D")
• Console.ReadLine()
• Case Else
• Dim intInput As Integer
• System.Console.WriteLine("Enter an integer…")
• intInput = Val(System.Console.ReadLine())
• Select Case intInput
• Case 1
• System.Console.WriteLine("Thank you.")
• Console.ReadLine()
• Case 2
• System.Console.WriteLine("That's fine.")
• Console.ReadLine()
• Case 3
• System.Console.WriteLine("OK.")
• Console.ReadLine()
• Case 4 To 7
• System.Console.WriteLine("In the range 4 to 7.")
• Console.ReadLine()
• Case Is > 12
• System.Console.WriteLine("Definitely too big.")
• Console.ReadLine()
• Case Else
• System.Console.WriteLine("Not a number I know.")
• Console.ReadLine()
• End Select
• End Sub
• End Module
• Option Strict On
• Option Explicit On
• Public Class Form1
• TextBox1.Name = txtInputScore
• Label1.Name = lblOutputGrade
• Button1.Name = btnClaculate
• Button1.Text = "Calculate"
• Sub Button1_Click() Handles btnCalculate.Click
• Dim score As Integer
• score = CInt(txtInputScore.Text)
• Select Case score
• Case 80 To 100
• lblOutputGrade.Text = "A"
• Case 60 To 79
• lblOutputGrade.Text = "B"
• Case 50 To 59
• lblOutputGrade.Text = "C"

• Case 45 To 49
• lblOutputGrade.Text = "D"
• Case 40 To 44
• lblOutputGrade.Text = "E"
• Case 0 To 39
• lblOutputGrade.Text = "F"
• Case Else
• lblOutputGrade.Text = "Error Message"
• End Select
• End Sub
• End Class
Ex 1
• Convert the following If statement to Select Case
statements
• If intTemp <= 32 then
• lblComment.Text = “Freezing”
• ElseIf intTemp > 80 then
• lblComment.Text = “Hot”
• Else
• lblComment.Text = “Moderate”
• End If
answer
• Select Case intTemp
• Case Is > 80
• lblComment.Text =“Hot”
• Case Is > 32
• lblComment.Text =“Moderate”
• Case Else
• lblComment.Text =“Freezing”
• End Select
• Note: when using a relational operator the word “Is” must be
used e.g Is>=100
• To indicate a range of constants use the word “To” e.g 80 To 99
• Multiple constants should be separated by commas.
Ex 2
• If intCount = 0 then
• MessageBox.Show (“No items entered”)
• Else If intCount<11 then
• MessageBox.Show (“1-10 items entered”)
• Else If intCount<21 then
• MessageBox.Show (“11-20 items entered”)
• Else
• MessageBox.Show (“More than 20 items entered”)
• End If
Answer
• Select Case intCount
• Case 0
• MessageBox.Show (“No items entered”)
• Case 1 to 10
• MessageBox.Show (“1-10 items entered”)
• Case 11 to 20
• MessageBox.Show (“11-20 items entered”)
• Case Else
• MessageBox.Show (“More than 20 items entered”)
• End Select.


Selection Control structures: Example

Select Case Statement Imports System


Module Module1
Sub Main()
Dim day As Integer
Console.Writeline(“Enter a number from 1 to 7 to represent a day of the week”)
• Syntax day = Console.Readline()
Select Case test_value Select Case day
Case 1
Case comparison_expression1 Console.WriteLine("Today is Sunday")
Case 2
statements1 Console.WriteLine(" Today is Monday")
Case comparison_expression2 Case 3
Console.WriteLine(" Today is Tuesday")
statements2 Case 4
Console.WriteLine("Today is Wednesday")
Case comparison_expression3 Case 5
statements3 Console.WriteLine("Today is Thursday")
Case 6
... Console.WriteLine("Today is Friday")
Case 7
Case Else Console.WriteLine("Today is Saturday")
else_statements Case Else
Console.WriteLine(" You have typed Something wrong")
End Select End Select
End Sub
End Module
Select Case Statement cont.
• Using Ranges in Select Case Statements
• The To keyword specifies a range of values that test_value should match
• Example:
Select Case gradeLevel
Case 1 To 3
writeline(“Junior “)
Case 4 to 6
writeline(“Middle”)
Case 7 To 8
Writelin(“High”)
Case Else
Writeline(“Invalid grade level”)
End Select
Select Case Statement cont.
• The following example code also make use of select case structure to
determine score grade of students:
Select Case intScore
Case Is >= 90
strGrade = "A"
Case 80 To 89
strGrade = "B"
Case 70 To 79
strGrade = "C"
Case 60 To 69
strGrade = "D"
Case 0 To 59
strGrade = "F"
Case Else
WriteLine("Invalid Score Entered")
End Select
Select Case Statement cont.

• Using Is keyword in a Select Case Statement


• The Is keyword lets you perform logical comparisons using the test
value. The word Is takes the place of the test value in the comparison
expression.
• The example of student grade level can be coded using the Is keyword
as follows:
Select Case Statement cont.
Select Case gradeLevel
Case Is <= 3
WriteLine(“Junior”)
Case Is <= 6
WriteLine(“Middle”)
Case Is <= 8
WriteLine(“High”)
Case Else
WriteLine(“Invalid grade level”)
End Select
Select Case Statement cont.
• The Case statement’s expression list can contain multiple expressions, separated
by commas as follows:

Select Case intNumber


Case 1, 3, 5, 7, 9
strStatus = "Odd"
Case 2, 4, 6, 8, 10
strStatus = "Even"
Case Else
strStatus = "Out of Range"
End Select
Select Case Statement cont.
• The Case statement can use test string values as follows:

Select Case strAnimal


Case "Dogs", "Cats"
MessageBox.Show("House Pets")
Case "Cows", "Pigs", "Goats"
MessageBox.Show("Farm Animals")
Case "Lions", "Tigers", "Bears"
MessageBox.Show("Oh My!")
End Select

• You can use the operators =, <>, <, <=, >, and >= in an Is
clause
Select Case Statement cont.
•Generally, the Select Case structure follows the following rules
•Each value list contains one or more of the following types of items separated by
commas.
1. a literal
2. a variable
3. an expression
4. an inequality sign preceded by Is and followed by a literal, variable, or expression
5. a range given in the form a To b, where a and b are literals, variables, or expressions.
Selection Control structures:
Select Case Statement
• Class Exercise
• Using Babcock grading system, write a VB.NET application to read a
test score, determine the letter grade and prints the grade using
Select Case statement.
• Hint:
Test Score Grade
80 – 100 A
60 – 79 B
50 – 59 C
45 – 49 D
40 – 44 E
0 – 39 F
• Branching statement interrupts the sequential flow
of the program execution and allow it to jump from
one portion of a program to another. It isused to
cause certain actions within a program if a certain
condition is met.e.g an example of branching
statements are Exit, Go to, If, Return, Select Case
• Iteration Statement are called looping statements. It
allows a group of statements to be executed more
than once e.g Do, For and For Each
Selection cont.
• Write a VB.NET console application to read a test score, calculates the
letter grade and prints the grade using
• If … THEN statement
• Select Case statement
Examples
• If then statement
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• If /Then/ End If
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• Print “ Authorities have been notified”
• End If
• If/ Then/ Else/ End If
• If Balance-Check< 0 Then
• Print “You are overdrawn”
• Print “ Authorities have been notified”
• Else
• Balance = Balance- Check
• End If

You might also like