Nothing Special   »   [go: up one dir, main page]

Conditional Statements and Loops in Visual Basic

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

CONDITIONAL STATEMENTS IN VISUAL BASIC

Conditionally executes a group of statements, depending on the value of an expression.


Types:
1.If...Then Statement
2.If...Then...Else Statement
3.Select case statement.

If...Then Statement:
Description:
The If...Then statement examines the truthfulness of an expression.
Syntax:
If ( expression ) Then
Statement
End If
The program examines a condition. This expression can be a simple expression or a
combination of expressions.
If the expression is true, then the program will execute the Statement.
There are two ways we can use the If...Then statement.
If the conditional formula is short enough, we can write it on one line, like this:

If expression Then Statement

If there are many statements to execute as a truthful result of the condition, we should
write the statements on alternate lines.
Of course, you can use this technique even if the condition you are examining is short.
In this case, one very important rule to keep is to terminate the conditional statement
with End If.

If expression Then
Statement
End If
Here is another way:

If Condition Then
Statement1
Statement2
Statementn
End If

VB comparison operators:
< Less Than
<= Less Than or Equal to
> Greater Than
>= Greater Than or Equal to
= Equal to
<> Not Equal to

Example:
Private Sub Command1_Click()
Dim var1 As Integer
var1 = 10

If var1 = 10 Then
MsgBox "The condition is true."
End If
End Sub

If....Then....Else statement:
Description:
The If...Then statement offers only one alternative: to act if the condition is true.
Whenever we would like to apply an alternate expression in case the condition is false we
can use the If...Then...Else statement.

Syntax:
If ( expression ) Then
Statement1
Else
Statement2
End If

When this section of code is executed, if the expression is true, then the first statement,
Statement1, is executed.
If the expression is false, the second statement, Statement2, is executed.

Example:
Private Sub Command1_Click()
Dim var1 As Integer
var1 = 5
If var1 = 10 Then
MsgBox "The variable is ten"
Else
MsgBox "The variable is not ten"
End If
End Sub

The expression is evaluated. If the resulting value is non-zero, the statement(s) after the
Then are executed.
If there is an Else and if the expression evaluated to zero, the statement(s) after the Else
are executed.

Nested If statement:
Description:
The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it
offers as many choices as necessary.

The formula is:


If ( expression = value_1 ) Then
Statements_1
ElseIf ( expression = value_2) Then
Statements_2
ElseIf ( expression = value_3) Then
Statements_3

Else
Statements_default
End If

The program will first examine expression1.


If expression1 is true, the program will execute Statments1 and stop examining
conditions.
If expression1 is false, the program will examine expression2 and act accordingly.
Whenever a condition is false, the program will continue examining the conditions until it
finds one.
Once a true condition has been found and its statement executed, the program will
terminate the conditional examination at End If.

Example:

Private Sub Form_Click()


If BackColor = vbRed Then
BackColor = vbBlue
ElseIf BackColor = vbBlue Then
BackColor = vbGreen
ElseIf BackColor = vbGreen Then
BackColor = vbBlack
Else
BackColor = vbRed
End If
End Sub

Select statement:
Description:
If we have a large number of conditions to examine, the If...Then...Else will go through
each one of them.
Visual Basic offers the alternative of jumping to the statement that applies to the state of
the condition.

Syntax:
The formula of the Select Case is:

Select Case Expression


Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionk
Statementk
End Select

The Expression will examined and evaluated once.


Then it will compare the result of this examination with the Expression of each case.
Once it finds one that matches, it would execute the corresponding Statement.

If there could be no match between the Expression and one of the Expressions,use a Case
Else statement at the end of the list.
The statement would then look like this:

Select Case Expression


Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionk
Statementk
Case Else
Statementk
End Select

Example:
Private Sub Form_Click()
Select Case BackColor
Case vbRed
BackColor = vbBlue
Case vbBlue
BackColor = vbGreen
Case vbGreen
BackColor = vbBlack
Case Else
BackColor = vbRed
End Select
End Sub
IN-DETERMINANT LOOP IN VISUAL BASIC

 Indeterminate loops repeat an unknown number of times.


 Indeterminate loops run for an unknown number of repetitions until a condition is
true or while a condition is true.
 Four types of indeterminate loops

1.do while.... loop


2. do....until loop
3.while....wend loop
4.Do.....loopwhile

DO......WHILE LOOP STATEMENT IN VISUAL BASIC


Description:

 The Do While...Loop is used to execute statements until a certain condition is met.


 Syntax:

Do While (Expression)
(Code to execute)
Loop

 (Expression) can be any legal logical expression that we wish to evaluate to


determine whether or not to exit the loop.
 Each time the program reaches Loop it will verify that this expression is True, and if
it is False, it will exit the loop.
 Thus, instead of exiting when an expression is True, it now exits only once this
expression is false.

Example:
The following Do Loop counts from 1 to 100.

Dim number As Integer


number = 1
Do While number <= 100
number = number + 1
Loop

 A variable number is initialized to 1 and then the Do While Loop starts.


 First, the condition is tested; if condition is True, then the statements are executed.
 When it gets to the Loop it goes back to the Do and tests condition again.
 If condition is False on the first pass, the statements are never executed.

DO........UNTIL LOOP IN VISUAL BASIC


 Unlike the Do While...Loop and While...Wend repetition structures, the Do Until...
Loop structure tests a condition for falsity.
 Statements in the body of a Do Until...Loop are executed repeatedly as long as the
loop-continuation test evaluates to False.

Syntax:
Do Until (Expression)
(Code to execute)
Loop

 (Expression) can be any legal logical expression that we wish to evaluate to


determine whether or not to exit the loop.
 Each time the program reaches Loop it will evaluate this expression.
 If the expression is True, it will exit the loop , but otherwise it will continue looping.

Example for Do Until...Loop statement:


The coding is typed inside the click event of the command button

Dim number As Long


number=0
Do Until number > 1000
number = number + 1
Print number
Loop

Numbers between 1 to 1000 will be displayed on the form as soon as we click on the
command button.

WHILE......WEND IN VISUAL BASIC


DESCRIPTION:

 A While...Wend statement behaves like the Do While...Loop statement.


 Repeats the loop until the test condition is true,else it comes out of the loop for
false.

Syntax:

While (test condition)


code to execute
wend

Example:

The following While...Wend counts from 1 to 100

Dim number As Integer


number = 1
While number <=100
number = number + 1
Wend

DO......LOOP WHILE IN VISUAL BASIC


DESCRIPTION:

 The most basic form of loop in Visual Basic is the Do-Loop.


 Its construct is very simple:
 This, quite simply, executes the block of code, and when it reaches Loop, returns to
the beginning of the Do Loop and executes the same block of code again.
 The same block of code will be repeatedly executed until it is told to stop
executing.
 The Do...Loop While statement first executes the statements and then test the
condition after each execution.

Syntax:
Do
(Code to execute)
Loop while (test condition)

Example:

Dim number As Long


number = 0
Do
number = number + 1
Loop While number < 501

 The programs executes the statements between Do and Loop While .


 Then it determines whether the counter is less than 501.
 If so, the program again executes the statements between Do and Loop While else
exits the Loop.

FOR LOOP IN VISUAL BASIC


loop:

 repeating the number of operation a fixed number of times or until condition is


satisfied is called a loop.

Determinate Loops:

 will repeat themselves a known (specific) number of times (For..Next Loops)

The For...Next Loop

Description:
 The For...Next Loop is another way to make loops in Visual Basic.
 It comes under the category of determinant loop which means number of times loop
repeats is known.
 Repeats a group of statements a specified number of times.

Syntax:
For counterVariable = fromValue To toValue step stepvalue
...VB Statements...
Next counterVariable

 countervariable-keeps count on the loop


 fromvalue-start value of the for loop
 tovalue-end value of the for loop
 when the difference between first number and second number is > 1 then use step
to provide the difference.
 default step value is 1
 when you want decrement counter provide the step value in negative.
 when you want increment counter provide the step value in positive.

Example:
The following loop counts the numbers from 1 to 100:
Dim x As Integer
For x = 1 To 50
Print x
Next

In order to count the numbers from 1 to 50 in steps of 2, the following loop can be used

For x = 1 To 50 Step 2
Print x
Next

The following loop counts numbers as 1, 3, 5, 7..etc

The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.

For x = 1 To 50
Print x & Space$ (2);
Next

To increase the space between the numbers increase the value inside the brackets after
the & Space$.

Following example is a For...Next repetition structure which is with the If condition used.

Dim number As Integer


For number = 1 To 10
If number = 4 Then
Print "This is number 4"
Else
Print number
End If
Next

In the output instead of number 4 you will get the "This is number 4".

Early Exit of a For Loop

 It is often necessary to exit a For loop before it has completed the specified number
of loop iterations. This is achieved using the Visual Basic Exit For statement. This is
typically used in conjunction with a conditional If statement.
 The Following code example causes the loop to exit if the counter is equal to 3:

Dim intCount As Integer

For intCount = 0 To 5
If intCount = 3 Then Exit For
MessageBox.Show("Counter is currently: " + CStr(intCount))
Next intCount

Nested for:

 A loop can be coded within another loop thus forming nested loops.
 There can be many levels of nesting.
 nesting is possible as long as the inner structure is completely enclosed in the outer
structure.
 When nesting loops, each loop must have a unique counter variable.
 For example, nested loops are needed to display a table of values, to process the
elements of a two-dimensional array, or to sort array elements using the Bubble Sort
algorithm

Syntax:
for counter-variable1=start-value to end-value[step step-value]
statements......
for counter-variable2=start-value to end-value[step step-value]
statements......
next counter-variable2
next counter-variable1

Example:
To print the elements of an 2x2 array

for i=1 to 2
for j=1 to 2
print a(i,j),
next j
print
next i

You might also like