• UNIT 9: VARIABLES, OPERATORS, EXPRESSIONS AND CONTROL STRUCTURES.

    Key Unit Competency

    To be able to use variables, operators, expressions and control structures in a Visual Basic program.

    INTRODUCTORY ACTIVITY

    The Visual Basic program below asks the user to enter the names, year of birth and the sex and displays the following messages: “Good Morning Sir, you are .... years old” if the sex is Male and “Good morning Madam, you are ...years old” Analyze the following VB

    source code and answer corresponding questions:

    Private Sub Command1_Click()

    Dim names, sex As String

    Dim year As Integer

    names = Text1.Text

    sex = Text2.Text

    year = Val(Text3.Text)m = 2018 - year

    If sex = “Male” Then

    Print “Good morning Sir , you are”; m; “ years old “

    ElseIf sex = “Female” Then

    Print “Good morning Madam ,you are”; m; “ years old “Else

    Print sex; “ sex does not exist!”End If

    End Sub

    1. List the variables used in the source code above

    2. What is the type of Visual Basic Data used in this source code?

    3. Describe operators used in the source code

    4. What is the control structure used in the source code?

    5. Draw the corresponding interface and give an output of the above source code

    9.1. Types of Visual Basic Data

    ACTIVITY 9.1

    In every program, a programmer declares variables with their data types.

    1. Explain why the declaration of variables is important during the writing of programs

    2. What are the data types used in programs?

    3. Discuss the storage size and range of values of data types used in programs.There exist many types of variables, but the most used in Visual Basic are:

    • An elementary data type, such as Boolean, Long, or Decimal

    • A composite data type, such as an array or structure

    • An object type, or class, defined either in current application or in another application All the above types are grouped in two major data types: numeric data type and non-numeric data type.

    9.1.1 Numeric data types

    Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide among others.


    9.1.2 Non-numeric data types

    Non- numeric data types are types of data that cannot be manipulated mathematically using standard arithmetic operators. The non- numeric data types comprise of text or string data types, the Date data types, the Boolean data types, Object data type and Variant data type.

    Suffixes for literal

    Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double.

    In some cases, a literal can be forced to a particular data type; for example, when assigning a particularly large integral literal value to a variable of type decimal, the following example produces an error:

    Dim myDecimal as Decimal

    myDecimal = 100000000000000000000 ‘ This causes a compiler error. The error results from the representation of the literal. The Decimal data type can hold a value this large, but the literal is implicitly represented as a Long, which cannot.To make the previous example work, you can append the D type character to the literal, which causes it to be represented as a Decimal:

    Dim MyDecimal AsDecimal = 100000000000000000000DSo, a suffix needs to be added behind a literal so that VB can handle the calculation more accurately. If a suffix is not added behind a literal, it generates a syntax error. For example, num = 2.3807# is used for Double data type. The Table 9.3 below shows Visual Basic Data Types and their suffixes or Appended type char-acter

    Note: String literals are normally enclosed within double quotations while date and time literals are enclosed within two # sign. Strings can contain any characters, including num-bers. The following table summarizes the data types with their enclosing characters and appended type charactersTable 9.4: data types with their enclosing characters and appended type characters

    APPLICATION ACTIVITY 9.1

    1. What would happen if a programmer uses one of VB keywords (reserved words) as a variable identifier?

    2. In a program, if a user declares an integer variable and enters a string like “book”, explain the nature of the results produced by such a program

    3. Study the following VB source code, draw its corresponding interface and then give an output.

    Private Sub Form_Load()

    Form1.Show

    Name1 = “ UWIHANGANYE”

    phone = “ +250783297650”

    Jour = #7/29/1996#

    BithTime = #7:20:00 PM#

    Text1.Text = Name1

    Text2.Text = phone

    Text3.Text = Jour

    Text4.Text = BithTime

    End Sub

    9.2 Variables

    ACTIVITY 9.2

    1. Outline different rules of naming a variable in Visual Basic

    2. Explain general format of variable declaration

    3. Explain general format of variable initialization

    4. Draw interface and write a VB program which asks a user for entering a radius of a circle to display the area of a circle after running the program as shown in figure 9.1. Consider pi as the constant whose numeric value 22/7.


    A variable is a name assigned to a data storage location. It can also be defined as area allocated by the computer memory to hold data. Variables are used in Visual Basic to store various kinds of data during program execution.

    9.2.1 Variable name

    In Visual Basic Program, each variable must be given a name. To name a variable in Visual Basic, there is a set of rules to be followed.The rules used in naming variables in Visual Basic are:

    • No more than 40 characters

    • Variables must include letters, numbers and underscores egg. No punctuation, spaces or other characters are permitted.

    • A variable name must begin with a letter

    • The name cannot be a reserved word (words needed by Visual Basic).

    For example, End is a reserved word in Visual Basic and therefore should not be used as a variable name.Examples of valid and invalid variable names are displayed in the table below:

    9.2.2 Variable declaration

    They are three ways for declaration of a variable.

    1. Default Declaration

    If the variables are not implicitly or explicitly declared, they are assigned the variant (a var-iable that can hold data of any size or format) type by default. The variant data type is a special type used by visual basic that contains numeric, string or date data.For example: the following VB program finds the sum of two given numbers:

    Private Sub Command1_Click()

    Dim n1, n2, sum As Variant

    n1 = Val(Text1.Text)

    n2 = Val(Text2.Text)

    n3 = n1 + n2Text3.Text = n3

    End Sub

    2. Implicit Declaration

    To implicitly declare a variable, use the corresponding suffix. For example:

    declaration way, Visual Basic will take care of ensuring consistency in upper and lower case letters used in variable names.

    To explicitly declare a variable, its scope has to be firstly determined. There are four levels of scope are procedural level, static, form and module level, and last global level

    These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest scope means the smallest set of code that can refer to the element without qual-ification.

    a) Procedure level

    With procedure level, variable are declared using the Dim statement Example:

    Dim MyName As String

    Dim MyInt As Integer

    This is given to variables declared using the Dim reserved word within a block of statemet

    Here, the variable can only exist and be used within the If ... Then ... Else statement. It is a local variable visible only inside the block where it has been declared.

    b) Procedure level scope, static

    In procedure level ,static, variables declared in this manner do not retain their value once a procedure terminate, within a procedure level, static variables are declared using the Dim statement

    For example:

    Private Sub End_click()

    Static age As Integer

    Static MyName As string

    end sub

    Note that

    Dim can only exist and be used within the procedure or function. It is a local variable in that procedure or function.

    • Procedure level variables declared in this manner do not retain their value once a pro-cedure terminates.

    • To make a procedure level variable retain its value upon existing the procedure, replace the Dim keyword with Static

    c) Form(module) level scope

    The variable is declared in the General Declarations section at the start of the module. Form (module) level variables retain their values and are available to all procedures within that form.

    Module level variables are declared in the declarations part of the general object in the form’s (module’s) code window. The Dim keyword is used.

    Example1: Dim MyDate as Date

    Example 2: a program which requires three numbers entered from keyboard then calcu-lates their sum and average.

    Requirements to perform the asked question;Design interface containing five Text box with their corresponding labels and four com-mands representing sum, agerage clear and exit respectively least but not last assign prop-erties to each control and last attach code

    VB Source code can look as follows :





    d) Global level scope

    This is given to variables declared using the public reserved word within a code module. The variable is declared in the General Declarations section at the start of the module. Glob-al level variables retain their value and are available to all procedures within an application.It is advisable to keep all global variables in one module. Use the Global or public keyword.

    Examples: Global MyInt as Integer or Public MyInt as Integer
    Notice that several variables can be declared in one statement without having to repeat the data type. In the following statements, the variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single:

    Dim i, j, k As Integer
    ‘All three variables in the preceding statement are declared as Integer.
    Dim l, m As Long, x, y As Single
    ‘In the preceding statement, l and m areLong, x and y are Single.

    Variable initialization

    Once a variable is declared, it does not have a defined value, hence it cannot be used until it is initialized by assigning it a value.
    Thus, variable initialization is the process of providing or assigning value to the variable
    Where Variablename is the descriptive name of the variable, = is the assignment operator and value is the value that a variable will contain.


    9.2.4 Declaring Constants

    constants is value in memory that does not change during program execution. For example, in mathematics, pi is a constant whose numeric value is 22/7.The declaration of a constant goes immediately with its initialization.

    Syntax: Const constant name As data type = value





    9.3 Scope of a variable

    Learning Activity 9.1
    As any other programming language, Visual Basic application acts on data stored in variables. Using internet and library textbooks, discuss different scopes of variables.

    APPLICATION ACTIVITY 9.2

    1. Study the given VB source code of a program that requires a positive integer and displays its factorial. To avoid possible memory overflow, replace the “fact” variable data type with an appropriate data type whose size can hold a large value.




    2. Write a VB program that asks to enter a radius of a sphere and display its volume. Declare Pi as a constant variable and assign to it 22/7 value.
    3. Write a VB program that requests the user to enter 2 numbers and displays their sum, difference and product.

    The scope of a declared element is the set of all code that can refer to it without qualifying its name. It is an area of influence and lifetime for a variable. This means a period of existence dependent on where and how the variable is declared. An element can have scope at one of the following levels:


    In Microsoft Visual Basic for Applications, the three scopes available for variables are private, module, and public.

    9.3.1 Private (Local) Scope

    A local variable with private scope is recognized only within the procedure in which it is declared. A local variable can be declared with a Dim or Static statement.
    • When a local variable is declared with the Dim statement, the variable remains in existence only as long as the procedure in which it is declared is running. Usually, when the procedure is finished running, the values of the procedure’s local variables are not preserved, and the memory allocated to those variables is released.
    • A local variable declared with the Static statement remains in existant the entire time Visual Basic is running. Local variable retains its value after the module has finished executing.

    9.3.2 Module (Global) Scope

    A variable that is recognized among all of the procedures on a module sheet is called a “module-level” variable. A module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules. A module-level variable re-mains in existence while Visual Basic is running until the module in which it is declared is edited. Module-level variables can be declared with a Dim or Private statement at the top of the module above the first procedure definition.




    9.3.3 Public scope

    Public variables have the broadest scope of all variables. A public variable, like a module-lev-el variable, is declared at the top of the module, above the first procedure definition. A pub-lic variable cannot be declared within a procedure. A public variable is always declared with a “Public” statement. A public variable may be declared in any module sheet.


    APPLICATION ACTIVITY 9.3

    Write a Visual Basic program which computes the sum and average of the three given integers using keyboard.To achieve this, follow the instructions below:
    i. The program uses two different procedures addition () and moyenne ()
    ii. Declare the 3 variables as local variables in addition () procedure
    iii. Declare sum as global variable to hold the sum calculated by addition() procedure
    iv. The moyenne () procedure calculates the average of three given integers and display it.

    9.4 Operators and expressions in Visual Basic

    ACTIVITY 9.4
    1. Enumerate the various operators used in C++ programming language
    2. What is the value of the following expression if x=10 and y=5?
    3. Evaluate the following expression if A=10, B=5, C=0 and D=22(A AND B)OR(C OR D) AND A

    In programming context, an operator is a symbol or a keyword that instructs a compiler to evaluate mathematical or logical expressions.A Visual Basic expression is a combination of operators and operands.
    For example, in the expression: energy = mass * light_speed ^2
    • Energy, mass ,light_speed and 2 are the operands while
    • = is the assignment operator, * is multiplication operator and ^ the exponentiation arithmetic operator.

    9.4.1 Arithmetic operators

    The most common operators in Visual Basic are the arithmetic operators. Table 9.4 below gives a summary of arithmetic operators supported in Visual Basic.


    Note that:
    • Parentheses () can change the precedence
    • To concatenate two strings, use the & symbol or the + symbol: txtSample.Text=”My country“+“is”+ “Rwanda” myname=”John” & “Mugabo”

    9.4.2 Relational (Comparison) operators

    Normally, they are used to compare data values and then the result helps to decide what action to take. The result of comparison operation is a Boolean value (True or False).


    AND: An expression has a true value if both operands are true, and false value elsewhere
    OR: An expression has a true value if at least one of the operand is true and false elsewhere.
    Xor: An expression has a true value if both operand are different and has a false value if both operands are the same.
    NOT: Negates Boolean operand


    The following example of VB program illustrates the Not ,And,Or,and Xor operators




    Note that The AndAlso Operator is very similar to the And operator, in that it also performs logical conjunction on two Boolean expressions. The key difference between the two is that AndAlso exhibits short-circuiting behavior. If the first expression in an AndAlso expression evaluates to False, then the second expression is not evaluated because it cannot alter the final result, thus AndAlso returns False.
    Similarly, the OrElse Operator performs short-circuiting logical disjunction on two Boolean expressions. If the first expression in an OrElse expression evaluates to, then the second expression is not evaluated because it cannot alter the final result, and OrElse returns True.

    9.4.3 Bitwise operators

    Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and then assign values based on the comparison. Bitwise operators are similar to logical operators only that they are specifically used to manipulate binary digits.


    Example:
    Consider the expression below:
    x = 5 Or 6
    5 in binary form = 1016
    in binary form = 110101
    And 110 = 100

    The bitwise And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. The result is treated as decimal. The value 100 is the binary representation of 4, so x = 4.
    The bitwise Or operator takes a 1 and assigns to the result bit if either or both of the compared bits is 1.


    Example: Consider the expression below:
    x = 5 Or 6
    101 (5 in binary form)
    110 (6 in binary form)
    111 (The result, in binary form)

    The result is treated as decimal. The value 111 is the binary representation of 7, so x =7.
    • Bitwise Not takes a single operand and inverts all the bits, including the sign bit, and assigns that value to the result. This means that for signed positive numbers, Not always returns a negative value, and for negative numbers, Not always returns a positive or zero value.

    Example: Dim x As Integer
    x = Not 5101 (5 in binary form) , its negation is 010The result is treated as decimal. The value 010 is the binary representation of 2, so x =2.
    Bitwise Xor assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1.

    Example:Dim x As Integer
    x = 5 Xor 6101 (5 in binary form)
    110 (6 in binary form)
    011 (The result, in binary form)The result is treated as decimal. The value 011 is the binary representation of 3, so x =3.

    • The AndAlso and OrElse operators do not support bitwise operations.The following example of VB program illustrates the use of bitwise operators



    9.4.4 Precedence of operators

    When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.
    Precedence Rules:
    When expressions contain operators from more than one category, they are evaluated ac-cording to the following rules:
    • The arithmetic and concatenation operators have greater precedence than the comparison, logical, and bitwise operators.
    • All comparison operators have equal precedence, and all have greater pre-cedence than the logical and bitwise operators, but lower precedence than the arithmetic and concatenation operators.
    • The logical and bitwise operators have lower precedence than the arithme-tic, concatenation, and comparison operators.
    • Operators with equal precedence are evaluated left to right in the order in which they appear in the expression
    Just like in BODMAS, the order of precedence can be changed by use of parenthesis.




    Note that:
    • The string concatenation operator (&) is not an arithmetic operator, but in precedence it is grouped with the arithmetic operators.
    • When operators of equal precedence appear together in an expression, for example multiplication and division, the compiler evaluates each opera-tion as it encounters it from left to right. The following example illustrates this.


    APPLICATION ACTIVITY 9.4
    1. Study the following program and determine the output after its execution


    2. Perform bitwise And, Or and Xor on the following variables
    a. S = 25, T = 31
    b. X = 50, Y = 18

    9.5. Decision structures in Visual Basic

    Learning Activity 9.5
    1. Discuss the use of decision control structures (If...Then, If... Then... Else, Nested If ... Then.... Else ...Statements) in Visual Basic programming
    2. Using Visual Basic, write a program that prompts a user to enter a student’s score in Mathematics. If the score is above 45%, the program should display “Pass” otherwise it should display “Fail”

    To implement an application in visual basic, you need several coding structures to control the program flow. The control structures are used to control the flow of execution of a pro-gram they are used in a program to repeat a set of operations (looping control structures), and for making decisions according to the conditions when a program is executing (deci-sion control structures). A decision structure will test a condition and then perform opera-tions depending on whether yes or not the condition is met (True or false).

    9.5.1 Types of decision control structures

    Decision control structures also known as selection control statements are conditional logic used when there is one or more options or alternatives to chose from. There are four types of decision control structures namely if...then, if...then else, nested if ....then else, and select case

    A. If ..... Then statement


    B. If .....Then ....Else statement
    The If...Then...Else selection structure allows the programmer to specify that different ac-tions are to be performed when the condition is True than when the condition is False. If the condition is true, the first part of the if ...then is executed. However if the condition is false the block of the else statements is executed

    The syntax of the If ...Then ...Else conditional statement is as follows:




    C. Nested If ....Else statement
    Nested If...Then...Else statement test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures
    The syntax of the Nested If ...Else




    In using branching statements, be aware that each IF and Else If in a block is tested sequen-tially. The first time an If test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also True, it will never be considered.
    Example:
    Write a program to read marks (per cent) of university students and put these students into classes according to their marks. Classes with their corresponding marks:
    • From 80 to 100: First class honours
    • From 70 to 79: Upper second class honours
    • From 50 to 69: Lower second class honours
    • From 40 to 49: Pass
    • Below 40: Fail

    Solution:





    APPLICATION ACTIVITY 9.5
    1. Create a simple program which will ask a user to input a value.
    • If the value is 1 it should display the text “The day is Monday”
    • If the value is 2 it should display the text “The day is Tuesday”
    • Do this for all the days of the week.
    • Use the Nested If...Then ...Else structure to achieve the above.
    2. Write a VB program that would enable the user to enter student marks in three subjects. The program should calculate mean marks and determine whether the student has passed if the pass mark is 50%
    3. Observe the following interfaces and write a visual basic program using various mathematical functions like sqrt, sqr, sin, cos, tan.\





    Hint: Once the user enters any value in the first Textbox and selects any option, the output will be displayed in second TextBox, if the user enters a negative number and selects the sqrt option he/she will be informed that the square root of a negative number does not exist and once he or she does not select any option he/she will be informed to select any of available option.

    D. Select case statement

    Learning Activity 9.6

    1. Discuss the use of Select case statement as decision control in Visual Basic programming
    2. Create a simple program which will ask a user to input a value.
    • If the value is 1 it should display the text “The month is January”
    • If the value is 2 it should display the text “The month is February”
    • If the value is 3 it should display the text “The month is March”
    • If the value is 4 it should display the text “The month is April”
    • Do the same for all months of a year
    • Use the Select case statement to achieve the above

    Select...Case structure is an alternative to nested If...Then...Else for selectively executing a single block of statements from among multiple block of statements. If the “case” matches the condition is selected and all instructions within the matching case are executed. Select...case is more convenient to use than the If...Else...End If.The general format is:


    Each possible value of the item is checked using a Case statement followed by one or more Visual Basic statements that will be carried out if there is a match for that value. The final part of the structure is usually a Case Else statement to be executed if none of the above values match. This is useful for informing the user that he /she is out of cases.

    Example 1: A Visual Basic program that displays the Grade according to the marks entered by students:











    Example 2: Application to assign grade (comment) to students depending upon the marks they’ve got.











    APPLICATION ACTIVITY 9.6

    1. Write a VB program that displays the comment according to the entered student’s grade 


    2. Write a VB program that allows a user to enter two floating point number from the keyboard and it requests a user to enter his/her preference in order to perform one operation from (addition, subtraction, multiplication and division) operation’s menu. The program will display the result of an operation.

    Interface of your program should be similar to the following:


    9.6 Repetition structures

    Learing Activity 9.7
    3. With an example, explain the use of the following loops in Visual Basic programming:
    • Do While Loop
    • Do Until.... Loop
    • While loop
    • For loop
    4. Write a program that prints the numbers divisible by 5 and 3 in the range from 1 to 205. Using Do ... Loop While, write an application that prints not divisible by 5 in the range from 1 to 10

    Repetitions also known as iterations or loops are structures that allow a statement or group of statements to be carried out repeatedly while some conditions remain true (or for a specified number of times)
    They are two basic iteration structures:
    a. Pre-test iterations: in these loops, the condition to be met occurs at the beginning of the loop and the code will not run at all if the condition is never met. This can be implemented using: For ... Next, Do While .... Loop, Do Until ... Loop and While ... Wend loop
    b.Post –test iterations: in these loops, the condition to be met is at the end of the loop so that the code always runs at least once. This can be implemented using the: Do ... Loop While, Do ... Loop Until
    Visual Basic supports two types of loops which are indeterminate loops and determinate loop

    9.6.1 Indeterminate loops

    These are loops which repeat until a predetermined goal is achieved. Repeating until some initial conditions change. The Indeterminate loops supported in VB are the following:

    i. Do While ... Loop



    When Visual Basic executes this Do While ... Loop, it first tests condition. If condition is False, it skips past all the statements. If it’s True, Visual Basic executes the statements and then goes back to the Do while statement and tests the condition again. Consequently, the loop can execute any number of times, as long as condition is True. The statements never execute if initially is False.

    Example: a visual basic program to find the sum of number from 0 to 100


    ii. Do Until ... Loop

    Unlike the Do While...Loop and While...end loop structures, the Do Until... Loop structure tests a condition for falsity. Statements in the body of a Do Until...Loop are executed re-peatedly as long as the loop-continuation test evaluates to False. The general format is:



    ii. While .... Wend

    A While...Wend statement behaves like Do While...Loop statement. It executes a set of VB statements till the condition evaluates to true.



    iv. Do ... Loop While

    The Do...Loop While statement first executes the statements and then test the condition after each  execution.


    The programs executes the statements between Do and Loop While structure in any case. Then it determines whether the number is less than 20. If so, the program again executes the statements between Do and Loop While, else exits the Loop.

    v. Do ... Loop Until

    The general format is:


    Figure 9.21: Loop results

    APPLICATION ACTIVITY 9.8

    1. By using:
    • Do While.... Loop
    • While ...Wend loop
    • Do ... Loop Until

    Write a VB program that computes the sum of even numbers from 0 to 50.2. Write a VB program that displays the product of even numbers and product of odd numbers between 1 to 15 numbers.

    9.6.2 Determinate loop

    ACTIVITY 9.9
    1. Give and explain the syntax of for... Next loop in VB2. Write a program that reads a number from user and displays the table of that number.
    2 X 1 = 2
    2 X 2 = 4
    2 X 3 = 6

    . . . . .
    2 X 9 = 18
    2 X 10 = 20

    This loop repeats a set of operations a fixed number of times. The common used terminate loop is For ....next loop.



    In this syntax statement, For, To, and Next are required keywords, and the assignment oper-ator is required. First, you replace variable with the name of a numeric variable that keeps track of the current loop count. Next, you replace start and end with numeric values that represent the starting and stopping points for the loop.
    The line or lines between the For and Next statements are the instructions that repeat each time the loop executes.For...Next loop structure handles all the details of counter-controlled repetition
    Example 1: Suppose you want to print the numbers from 1 to 10.The following lines of codes can be used in procedure.



    Example 2: VB application to display the multiplication tables of 5

    User interface:




    Creating Loops with a Custom Counter

    You can create a loop with a counter pattern other than 1, 2, 3, 4, and so on. First, you specify a different start value in the loop. Then, you use the Step keyword to increment the counter at different intervals. In this case the syntax for a For...Next loop looks like the following:
    For counter = initial To End Step [Increment]

    One or more VB statements

    Next [counter]

    The arguments counter, start, end, and increment are all numeric. The increment argu-ment can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If step isn’t set, then increment defaults to 1.


    The VB source code above prints this sequence of numbers: 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49
    Specifying Decimal Values You can also specify decimal values in a loop. For example:
    For i = 1 To 2.5
    Step 0.1
    Print i
    Next i
    The program above prints this sequence of numbers as follow:


    Note that:The exit statement allows you to exit directly from For Loop and Do Loop. Exit For can appear as many times as needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop (the Exit Do statement works with all versions of the Do Loop syntax).

    Sometimes the user might want to get out from the loop before the whole repetitive pro-cess is executed; the command to use is Exit For to exit a For.....Next Loop or Exit Do to exit a Do... Loop, and you can place the Exit For or Exit Do statement within the loop.The exit keyword in loop control statement is used as break Jump control statement in other programming languages to terminate prematurely the loop.

    a) Exit For
    The format is:
    For counter= start To end step (increment)
    Statements
    Exit for
    Statement
    Next counter




    Nested Loops
    • The nested loops are the loops that are placed inside each other.
    • The most inner loop will be executed first, then the outer ones.
    • Nested loops are very useful when there is a requirement to generate differ-ent kinds of patterns as output.


    For Each loop
    The For Each loop is a scope that defines a list of statements that are to be repeated for all items specified within a certain collection/array of items.
    The For Each loop, as compared to the For loop, can’t be used to iterate from a range of values specified with a starting and ending value.

    Syntax of a For Each Loop:

    For each variable in Items
    Vb codes
    Next variable
    Where:Variable is the iterating variable which is used to iterate through the elements of the col-lection or array
    Items: a collection or array of items
    Next: closing statement for the loop. Optionally you can specify the Iterator variable



    APPLICATION ACTIVITY 9.9
    1. Study the following program in Visual Basic and write its output:


    2. Write a VB program to display the following sequence of numbers 100,80,60,40,20,0
    3. Write a VB application that prints the numbers divisible by 5 or 3 but not both in the range from 1 to 20

    END UNIT ASSESSMENT

    1. Write a VB program to calculate the values of the following arithmetic operation if the user inputs two numbers M and N into two separate text boxes
    a. M^Nb.
    b.M\Nc.
    b.M Mod N
    2. Build an application to calculate the volume of the cylinder
    3. Differentiate nested if to switch case decision control structures
    4. Write a VB application that prints the numbers divisible by 5 or 3 in the range from 1 to 20
    5. Write a VB program that displays odd numbers between 1 to 30 numbers
    6. Design an application to compute the sum of the first “N” natural numbers.
    7. Draw an interface and write a VB application to check if a given number is prime or not.



    UNIT8: Introduction to Visual basicUNIT 10: INTRODUCTION TO JAVA