+ All Categories
Home > Documents > Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of...

Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of...

Date post: 20-Apr-2020
Category:
Upload: others
View: 5 times
Download: 0 times
Share this document with a friend
84
Programming using Visual Basic Express by Jeanette Patterson
Transcript
Page 1: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Programming using Visual Basic Express

by Jeanette Patterson

Page 2: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Contents Introduction 4 The IDE Getting Started 5

Chapter 1 The Basics 6

Chapter 2 Working with Data

• Variables • Arithmetic Operators • Concatenation • Sequence • Constants

8 8 11 13 13 14

Chapter 3 Selection • If Then Else • Comparison Operators • Logical Operators • Nested If Then Else • Select Case

17 17 18 19 22 23

Chapter 4 Iteration • For Next Loops • Post Conditioned Loops • Pre Conditioned Loops

26 26 31 34

Chapter 5 Chapter 6

Arrays • One Dimensional Arrays • Parallel Arrays • Two Dimensional Arrays • Enumerated Types • Sets

Subroutines

• Procedures • Functions

37 37 41 42 46 47 51 52 56

J Patterson 2

Page 3: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 7 Built in Functions 60

• String Handling 60 • Random Numbers 62

Chapter 8 Records 65

• Arrays of records 66

Chapter 9 File Handling 70 • File Organisation 70 • Text Files 73 • Potions Task 80

Chapter 10 Windows Form Applications 81

• Properties 83

J Patterson 3

Page 4: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Introduction Visual Basic is classed as an event driven, high level programming language which has been developed by Microsoft. It has its origins in BASIC Beginner's All-purpose Symbolic Instruction Code , which was an early all-purpose language developed to help students is science and maths use computers effectively. Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual Basic is a powerful development package, but we are going to use it as a tool to learn the basics of programming. This means that we will be able to transfer our skills to other languages and not be tied to one software proprietor. So what does event driven mean, I hear you say? It is a programming paradigm in which the flow of the program is dependent on events. Events can be things like clicking a button or loading a form. However, we will focus on using the console version of VB.Net as this will help us develop a good understanding of the fundamentals of programming. Practice and Programming Exercises You will need to write lots of programs to become a good programmer but some of you will love it and work fast. In this booklet I have written some extension exercises for those of you who are working ahead. If you don’t complete all the extension exercises don’t worry and work at your own pace. Most importantly, when first programming, you WILL get errors and problems. Therefore it is crucial that you ask for help when you need it, so you can move on. Once you have had the same error a few times you will learn how to deal with it. Do not be embarrassed, I still make mistakes and with programming, learning from our mistakes is how we make progress. Good luck and enjoy! J Patterson

J Patterson 4

Page 5: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

The Integrated Development Environment (IDE) These days most developers use an IDE. This is a term used to describe a programming environment that has been packaged as an application program, typically consisting of a basic text editor (where you write the code), a compiler (to turn your code into binary), a debugger (to help fix errors), and a graphical user interface (GUI) builder. The IDE may be a standalone application or often they are included as part of one or more existing and compatible applications such as Visual Studio. IDEs provide a user-friendly framework for many modern programming languages, such as Visual Basic and Java. Visual Basic Express – IDE We are going to use the console version of VB. This is a back to basics approach and it well help use learn how to code in a more structured manner, it is also compatible with what is required for the exam boards.

Click on New Project

And select Console Application

J Patterson 5

Page 6: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 1 – The Basics - Your first program

When you create a new Console Application project – you should see the following in the code editor. Module Module1 Sub Main() End Sub End Module Hello World! Type the code below into the window between the Main() and End Sub

statements. Console.Write("Hello World") Console.Read()

This code writes the text “Hello World” to the screen, and the “Read” keeps the window open. To keep your program, first of all save your work by pressing the following icon

Then debug your program by pressing the play icon on the top bar. This will check your code and then, if it is error free, it will run it.

Congratulations……You are a computer programmer!! Similar to Console.Write there is Console.WriteLine which inserts a carriage return. Experiment with both to see how they work. What is the difference? Try running one of your programs without Console.Read(). What happens?

J Patterson 6

Page 7: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercises

1. Write a program that will output two messages of your choice on the screen, on separate lines.

2. Write a program which writes out the letter “L” as shown below.

Sub Main() Console.WriteLine("*") Console.WriteLine("*") Console.WriteLine("*") Console.WriteLine("*") Console.WriteLine("*") Console.WriteLine("*") Console.WriteLine("*****") Console.Read() End Sub

3. Try a more complex letter of your choice Extension

4. Create a shape, such as a square , rectangle or even a triangle

J Patterson 7

Page 8: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 2 - Working with data

Variables

When you are running a program, any data that it uses must be stored in RAM. The address of where you store a piece of data in RAM is given an identifier (name) and is known as a variable.

Data Types Data Type Used for Storing Storage

Required (bytes)

Byte Whole numbers (small) + 1 byte

Integer Whole numbers + or -

4 bytes

Long Whole numbers (long) + or -

8 bytes

Single Numbers with decimal places + or - 4 bytes Double Numbers with decimal places + or - 8 bytes Char A single character 2 bytes String One or more characters Variable

length Boolean True or false values Platform

dependant Date and Time

Date and time 8 bytes

Decimal Very long real numbers + or -

16 bytes

Declaring Variables We need to do this so that Visual Basic knows what the identifier is and what type of data is being stored. Dim As are the VB keywords Dim Total As Integer Dim ForeName As String Dim Cost As Currency

J Patterson 8

Page 9: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

So when we declare a variable we are actually allocating a named space in memory( RAM) to hold the data. Note : When naming variables there is generally a convention and some rules to follow. Convention It is sensible to name variables so that it gives an indication of what type of data is being stored. Identifiers should not have any spaces, so when using adjoining words such as for a variable about a payment date, acceptable identifiers would be PaymentDate This format is sometimes known as Camel Case paymentDate Notice lower case on the first word payment_Date The use of underscore is often used to join words All of these methods are acceptable in VB, as it is not case sensitive, and they help to make a program more readable. You should stick to one however. Rules

• They should start with a letter • They may contain a mixture of letters and numbers • They may not contain punctuation, spaces or symbols • They should not contain any VB keywords (you will learn what these are

as you go) Task Create a new console application and enter the following Module Module1 Sub Main() Dim Num1 As Integer Dim Num2 As Integer Dim Sum As Integer Num1 = 5 Num2 = 3

J Patterson 9

Page 10: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Sum = Num1 + Num2 Console.WriteLine("The answer is " & Sum) Console.Read() End Sub End Module Run the program and check the answer. Change the values of Num1 and Num2 to check it works. There are a lot of important concepts in the above program; first of all let us look at our variables 8 5 3 Sum Num1 Num2 Declaring our variables (using Dim) sets up a “box” in memory for the data, remember all of these were declared as integers. Assignment When we say Num1 = 5 and Num2 = 8 what we are really doing is assigning the number 5 into Num1 and the number 8 into Num2. The calculation Sum = Num1 + Num2 should read, assign the value of Num1+Num2 into the variable Sum. So the “=” is what we call the assignment operator. The value to the right is what is stored in the variable that is identified on the left of the assignment operator. It can be read as “becomes equal to” or “takes the value”. So the following could be read as : 8 is assigned into X OR X takes the value 8 OR X becomes equal to 8

J Patterson 10

Page 11: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Arithmetic Operators

There is a range of arithmetic operations that we may need to perform on our data

Arithmetic Operator

Operation Can be applied to Resultant data type

Example Order of Precedence

+ Addition Integer, real Integer, real Num1 + Num2 6=

- Subtraction Integer, real Integer, real Num1– 1 6=

* Multiplication Integer, real Integer, real X * Y 3=

/ Division Integer, real Real X / 2 3=

\ Integer division Integer Integer 3 \2 4

Mod Modulus (Gives the remainder)

Integer Integer 8 Mod 3 5

- Negation Integer, real -23.6 2

^ Exponentiation Integer, real Integer X^Y 1

Enter the following program to see this at work Module Module1 Sub Main() Dim Num1, Num2, Sum, Sum2, Sum3, Sum4 As Integer Dim Sum1 As Single Num1 = 5 Num2 = 3 Sum = Num1 + Num2 Sum1 = Num1 / Num2 'normal division Sum2 = Num1 \ Num2 'integer division Sum3 = Num1 Mod Num2 'modulus (remainder) Sum4 = Num1 ^ Num2 Console.WriteLine("The answer is for addition " & Sum) Console.WriteLine("The answer is for division " & Sum1) Console.WriteLine("The answer is for integer division " & Sum2) Console.WriteLine("The answer is for modulus " & Sum3)

J Patterson 11

Page 12: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Console.WriteLine("The answer is for exponent " & Sum4) Console.Read() End Sub End Module

You should see a run screen like the following

Now try changing the values for Num1 and Num2 and see what happens.

Variable Declarations Global Global variables are variables declared at the beginning of the program and accessible from anywhere in the program. It is not always desirable to use a global variable as its values may get changed accidentally if you have multiple functions or procedures in your program. Local variables Rather than declaring variables globally, it is good programming style to declare variables locally within the block where the variable is going to be used. We will see more on this later!

Interacting with the User

Now we have some idea about declaring variables and how to use arithmetic operators, we need to think about making more user friendly programs.

Look at the following code

J Patterson 12

Page 13: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Module Module1 Sub Main() Dim Number1, Number2, Sum As Integer Console.Write("Please enter in a number: ") Number1 = Console.ReadLine Console.Write("Please enter another number: ") Number2 = Console.ReadLine Sum = Number1 + Number2 Console.WriteLine(Number1 & " + " & Number2 & " = " & Sum) Console.Read() End Sub End Module

Notice in the program the use of the Console.ReadLine statement this will store the data that the user has been asked to enter. Notice in this case it is being assigned into Number1 and Number2. Also notice the use of the “&” to concatenate the string. This makes the output more meaningful for the user.

Sequence All of our programs that we have written so far are executed by the computer one line after another. This is called sequence and is one of the major tools of structured programming. If you have managed this far then you have certainly understood the construct of sequence!!

J Patterson 13

Page 14: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Constants Sometimes there are values that we want to stay the same throughout the program. In Vb we can declare them as constants rather than variables at the beginning of the program in the const section, where you also initialise them.

Module Module1

Const VatRate = 0.2

Sub Main()

Dim cost, tax As Double

Console.WriteLine("Enter the cost of goods: ")

cost = Console.ReadLine

tax = cost * VatRate

Console.WriteLine("The VAT is £" & tax.ToString("N2"))

Console.Read()

End Sub

End Module

Advantages of using named constants rather than variables

• The value of a constant cannot be accidentally changed during the running of the program.

• The program runs faster because all references to the constant are replaced by its value at compile time, whereas a variable’s value has to be retrieved from main memory at run time.

Constants are declared before variables.

Rounds to 2 decimal places – indicated by “N2”

J Patterson 14

Page 15: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Advantages of using named constants rather than the actual value

• If the value needs to be changed at a later date, such as the VAT rate changes, only the constant declaration needs to be changed.

Now over to you!

Exercises

1. Write a program which declares 4 integer variables. Num1, Num2, Num3 and Result. Ask the user to input values for Num1, Num2 and Num3 and read those values into the appropriate variables. Write a formula to calculate (Num1-Num2)*Num3 and assign the answer into Result. Report the result to the user and ensure the dialogue with the user is friendly. (Hint : Use a string and concatenate it using &)

2. Write a program which enables the user to input the length and breadth of a rectangle and then calculates the area. Report the result to the user. All interaction with the user should be user friendly. (Hint: Remember the units!)

3. Write a program which will add up 5 different numbers and calculate the

average of those numbers. (Hints : Average would be a sensible variable name for your final result but remember calculating average can produce a decimal number, so think carefully about data types)

J Patterson 15

Page 16: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

4. Write a program to solve the following problem.....if there is a 2000Kg pregnant elephant that gives birth to a 200Kg calf but then eats 50Kg worth of food. How much does she weigh? Remember: to report the result in a user friendly manner.

Extension Tasks

5. Ask the user to enter prices for five items, calculate the total cost of the items, the VAT due and the total price including the VAT. (Hint: try to be as efficient as possible in your calculations)

6. Write a program to enter a temperature in degrees Fahrenheit and display the equivalent temperature in degrees Centigrade. Hint : The formula for conversion is Centigrade = (Fahrenheit – 32) * (5/9)

J Patterson 16

Page 17: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 3 - Selection – Decisions, Decisions Selection is the programming construct we can use if we need to take different routes through the code. The route will depend on various conditions. To do this you can use one of the following selection constructs Visual Basic provides:

If ... then

If ... then ... else

Select case

If … Then

When you want a program to execute a statement only if a certain condition is met, you use:

If BooleanExpression then statement

Reminder – a Boolean expression returns a Boolean value True or False. If the BooleanExpression is true the statement after then is executed.

Examples of Boolean expressions:

Age > 18

(Number > 10) And (Number <=25)

(X <=12) Or (Y>23)

(Year Mod 4 = 0) And (Not (Year Mod 100 = 0)

J Patterson 17

Page 18: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Comparison Operators

We use these operators all the time but they are really useful when programming

= equal to

<> not equal to

> greater than

< less than

>= greater than or equal to

<= less than or equal to

Look at the example below for using If …Then

Dim Number, Sum As Integer

Number = 1

If Number > 0 Then

Sum = Sum + Number

End If

Exercise

1. Write a program that reads in two numbers from the user and then displays a suitable message if both numbers are the same.

If … Then … Else

When you want your program to do one statement if a certain condition is met, and another statement if the condition is not met, you need to use:

If BooleanExpression Then statement1 else statement2

J Patterson 18

Page 19: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Example of an if … then … else statement program extract

If Number < 0 Then

Console.WriteLine("This is a negative number")

Else

Console.WriteLine("This is a positive number")

End If

Exercises

2. Adjust your answer to question 1 using an else to display a message indicating that the numbers are different.

3. Write a program that will read in a person’s age and display a message whether they are old enough to drive or not.

4. Write a program that asks the user to enter 2 numbers and displays the larger of the two numbers.

Logical Operators

You have used logical operators before when querying databases. In programming they enable us to join our comparisons together so that we can test more than one condition.

Operator Operation AND Condition1 AND Condition2

In this case both condition1 and condition2

need to be true in order for the whole expression to be true

Eg. If num > 10 AND y <40

Only if num is greater than 10 and y is less than 40 will the expression evaluate to true

OR Condition1 OR Condition2

J Patterson 19

Page 20: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

For the OR operation either condition1 or condition2 or both can be true in order for the whole expression to evaluate to true

Eg. if num =5 OR y >12

If num is 5 the expression is true If y is any number over 12 it is true

If num is 5 and y is any number over 12 it is true

NOT Using the NOT operator enables us to obtain the opposite of the expression

Eg. NOT y < 10

In other words if y is 10 or greater the expression will be true

Testing Multiple Conditions So far the if-then-else examples we have looked at have consisted of one test on a Boolean condition (ie True or False). A multiple Boolean condition can have two or more tests which can be true or false. To test more than one condition we can use our LOGICAL OPERATORS, these being AND, OR, NOT etc For example : When two or more conditions are joined by and AND operator, all conditions must be true to evaluate to TRUE. AND TASK : Open a new project and type in the following code Module Module1 Sub Main() Dim age As Integer Dim gender As Char Console.Write("Please enter the age :") age = Console.ReadLine Console.Write("What is your gender : ") gender = Console.ReadLine If (age >= 18) And (gender = "F") Then

J Patterson 20

Page 21: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Console.WriteLine("You can come in to the club") Else Console.WriteLine("Do not allow entry") End If Console.Read() End Sub End Module Run the program and try a few different inputs, you will need to, to test each path through the code. When two or more conditions are joined by an OR operator, at least ONE of the conditions must be true to evaluate to TRUE. OR TASK : Module Module1 Sub Main() Dim ticket As Char Dim memtype As String Console.Write("Does the member have a ticket? :") ticket = Console.ReadLine Console.Write("Enter membership type, gold or normal : ") memtype = Console.ReadLine If (ticket = "Y") Or (memtype = "gold") Then Console.WriteLine("You can come in to the club") Else Console.WriteLine("Sorry you are still not coming in") End If Console.Read() End Sub End Module

Run the program with a few different inputs, and take care this program is case sensitive. You could adjust it to take both lower and upper case.

J Patterson 21

Page 22: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

5. Write a program that checks whether a number input is within the range 15 to 30, inclusive, and displays an appropriate message.

Nested If statements

The statement in a then and/or else part of an if statement can itself be an if statement, this can occur often when you have a range of choices

For example:

If (letter >= "A" And letter <= "Z") Or (letter >= "a" And letter <= "z") Then

Console.WriteLine("Letter")

Else

If (letter >= "0" And letter <= "9") Then

Console.WriteLine("number")

Else

Console.WriteLine("I think that must be a special

character")

End If

End If

Exercises

6. Write a program, using a nested if then else, which will prompt the user for an age and display the following information based on the age typed in at run time.

O to 4 display a message to the user indicating below school age

5 to 9 display a message to the user indicating primary school age

10 to 13 display a message to the user indicating middle school age

14 to 16 display a message to the user indicating high school age

17 to 64 display a message to the user indicating working age

65 to 120 display a message to the user indicating retired

J Patterson 22

Page 23: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Select Case

You can use as many nested if statements as you need but this can get very cumbersome and it is often easier to use a case statement:

The basic structure of a select case is :

Select Case OrdinalExpression

Case <item or list>

Statement1

........

Case <item or list>

Statement2

Case else

Statement3

End Select

The value of the ordinal expression will determine which statement is executed. An ordinal expression just means that it must have an order like integers or letters. Each Case must be a constant, a list of constants or a subrange. Each value in the case must be unique in the case statement, and subranges and lists must not overlap. See examples below.

If Month is an integer variable:

Select Case month

Case 1, 3, 5, 7, 8, 10, 12

NoOfDays = 31

Case 4, 6, 9, 11

J Patterson 23

Page 24: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

NoOfDays = 30

Case 2

NoOfDays = 28

Case Else

Console.WriteLine("Not a month")

End Select

If letter is of type Char:

Module Module1 Sub Main() Dim letter As Char Console.Write("please enter a letter : ") letter = Console.ReadLine Select Case letter Case "A" To "Z", "a" To "z" Console.WriteLine("You entered a Letter") Case "0" To "9" Console.WriteLine("You entered a Number") Case Else Console.WriteLine("You typed in a Special Character") End Select Console.Read() End Sub End Module

Exercises

1. Write a program that asks the user for a month number and displays the number of days that month has (ignore leap years for now).

2. Write a program that lets the user enter a number between 1 and 12 and displays the month name for that month number. The input 3 would therefore display March.

3. Write a program that uses a select case instead of a nested if, for the school age question 6 in the if-then-else section

J Patterson 24

Page 25: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

4. Write a program that reads in an exam mark and displays the relevant

grade. The grade boundaries are: 0 to 40 marks grade U

41 to 50 marks grade E

51 to 60 marks grade D

61 to 70 marks grade C

71 to 80 marks grade B

81 to 100 marks grade A

Extension Tasks

5. Create a program that prompts the user for a real (decimal) number. The user should then be presented with a menu of what they want to do with their number. The menu should look like the following

Square the number Add ten to the number Cube the number Divide the number by two Quit Use the select case and your knowledge of performing calculations in Visual Basic to make sure that once the user has made their choice, the correct processing is carried out on the number.

6. Extend your program for Exercise 1 to include leap years. A year is a leap year if the year divides exactly by 4, but a century is not a leap year unless it is divisible by 400. For example the year 1996 was a leap year, the year 1900 was not, and the year 2000 was a leap year. (HINT: use the MOD operator and logical operators to help you)

J Patterson 25

Page 26: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 4 - Iteration (Repetition or Loops) There are a number of constructs that Visual Basic (and most other languages) offer to enable us to repeat a section of a program a number of times: For…. Next Do… Loop Until Do… Loop While Do… While Loop Do… Repeat Loop

We will start with the FOR NEXT loop Sometimes we may want to repeat a section of code a given number of times, we can use a For Next loop for that and they take the following general format

For Counter = StartValue to EndValue step [StepAmount]

Statement;

Next Counter

Counter is called the control variable and must be declared as an ordinal type, usually an integer. StartValue & EndValue must be expressions of the same data type as the control variable. The step amount is optional but will increment by ONE if no step amount is specified.

J Patterson 26

Page 27: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Look at the following program Module Module1 Sub Main() Dim i As Integer For i = 1 To 10 Console.WriteLine("My programs are") Console.WriteLine("Bug Free") Next i Console.WriteLine("I Hope") Console.Read() End Sub End Module

Can you predict what happens? Try running the code to check if you were right. Look at the next example; can you guess what will happen here? Module Module1 Sub Main() Dim counter As Integer For counter = 10 To 1 Step -1 Console.WriteLine(counter) Next counter Console.Read() End Sub End Module Hopefully you predicted that the numbers 10 down to 1 will be printed on a new line each time (as we used Console.Writeline) if we used Console.Write then we would get 10 to 1 going across the screen.

J Patterson 27

Page 28: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Console.Writeline Console.Write

Let’s look at one more example. This gives the user the opportunity to enter in 5 values and calculate a running total. Module Module1 Sub Main() Dim i As Integer Dim Number As Integer Dim Total As Integer For i = 1 To 5 Console.Write("Please enter a number: ") Number = Console.ReadLine Total = Total + Number Next i Console.WriteLine("The final total is : £" & Total) Console.Read() End Sub End Module The advantage here is that you don’t have to write the code to keep prompting the user each time, this is taken care of using the loop structure. It also keeps a running total until the loop is exited.

J Patterson 28

Page 29: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercises Remember to use a FOR NEXT loop

1. Ask the user to input their name and then print it to the screen 6 times.

2. Write a program which will allow the user to enter 5 numbers and then calculate the average of those numbers, informing the user of the final result.

3. Write a program that prompts the user to enter a short message and the number of times it is to be displayed and then displays the message the required number of times.

Extension Exercises

4. Write a program to display an ‘n times table’ for a given integer n. For n = 3, the output should be:

1 * 3 = 3

2 * 3 = 6

3 * 3 = 9

....

12 * 3 = 36

J Patterson 29

Page 30: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

5. Write a program using two nested for next loops (one inside the other)

that will produce the following pattern.

*1 **2 ***3 ****4 *****5 ******6 *******7 ********8

6. Now again using two nested for next loops, produce the following

pattern. 8******** 7******* 6****** 5***** 4**** 3*** 2** 1*

J Patterson 30

Page 31: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Post-Conditioned Loops NOTE : In post-conditioned loops the test comes at the end of the loop. DO …….LOOP UNTIL

In this type of loop the actions/statements are executed at least ONCE. Some condition with the loop will be tested, if the condition is false the loop will be repeated, otherwise the loop will terminate. The design for the next program is written in pseudocode, this can help us plan and think about what is required from our program. Task Write a program which will read in two numbers from the user, calculates their product and displays the answer. The program should continue to repeat these steps until the product is greater than 100. The program should then inform the user that it is quitting. Design Display “Program to find the product of two numbers” Do Read the first number Read the second number Multiply both numbers Display the product Until the product > 100 Display “Product greater than 100, program ending”

J Patterson 31

Page 32: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Implementation Module Module1 Sub Main() Dim Num1, Num2, Product As Integer Product = 0 'remember to initialise Do Console.Write("please enter a number : ") Num1 = Console.ReadLine Console.Write("please enter a number : ") Num2 = Console.ReadLine Product = Num1 * Num2 Console.WriteLine() Console.WriteLine(Product) Console.WriteLine() Loop Until Product > 100 Console.Write("program ending") Console.Read() End Sub End Module Notice the use of Console.Writeline() on its own to give some blank lines, which helps to space things out, creating a better user experience.

• Try running the above program and check that it LOOPS. We can also use a DO…… LOOP WHILE these loops are also post-conditioned and in fact it is just the way we interpret the condition which is different. So if we use a Do Loop While for the previous problem the condition would simply change to Do {Statements} Loop While Product <=100

J Patterson 32

Page 33: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Post Conditioned Loop Exercises 1. Write a program which will prompt the user to enter 3 numbers, which are

greater than zero. The program should add the numbers together and display the sum of the numbers. The program should continue to do this until the user enters the value zero. (This is often known as a rogue value, used to terminate the loop)

2. Write a program which will prompt the user for a number between 0 and

10. This program should validate that ONLY numbers in the valid range are allowed. If the number is valid then display, “This is a valid response”.

3. Write a program to print the numbers 20 down to -20.

Extension Exercise 4. Write a program which accepts a series of rainfall figures in mm. The

program should terminate when the total rainfall exceeds 250mm. The program should output the total rainfall and the number of days (entries) it took to exceed 250mm.

J Patterson 33

Page 34: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Pre-Conditioned Loops

NOTE: In Pre-Conditioned loops, the test comes at the beginning of the loop. DO UNTIL…..LOOP and DO WHILE……LOOP In this type of loop, if the condition (test) is not fulfilled, then the loop may not be executed at all. In addition, the variables which are used in the test must have valid values before the test statement, as well as inside the loop. The statements of the loop are executed if the conditional test is true and are not executed if the test is false. Look at the following example. Module Module1 Sub Main() Dim Num1, Num2, Answer As Integer Console.Write("please enter a number : ") Num1 = Console.ReadLine Console.Write("please enter a number : ") Num2 = Console.ReadLine Do While Num2 <> 0 Answer = Num1 \ Num2 Console.WriteLine() Console.WriteLine("The answer is " & Answer) Console.WriteLine() Console.Write("please enter a number : ") Num1 = Console.ReadLine Console.Write("please enter a number : ") Num2 = Console.ReadLine Loop Console.Write("Goodbye") Console.Read() End Sub End Module

Integer Division

Notice how the user is prompted

again before the end of the

loop

J Patterson 34

Page 35: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

In the above program the user is prompted for 2 numbers and the first number is divided by the second using integer division. The result of this division is then printed to the screen and the process is repeated. The method for terminating the loop is to enter zero for the second number. It makes sense that if zero is typed in for Num2 before the loop, then the loop will not be executed.

• Try running the code above and to ensure that all inputs are working correctly, use the following test data.

Num1 Num2 Answer 4 2 2 19 4 4 0 10 0 87 0 Goodbye

Pre-Conditioned Loop - Exercises 1. Write a program to calculate the gross wage for employees, given the rate

of pay as a constant of £12.66 and the hours worked, which are input by the user. The program terminates when the hours worked is less than zero The following design in pseudocode may help you Begin Declare Variables Declare Constants Prompt the user for hours worked While the hours worked are greater than zero Calculate and output the gross wage Prompt the user for the next employees hours worked End While End Program

J Patterson 35

Page 36: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

2. An organisation has approximately £4000 to allocate, in small amounts, to a

range of local charities. Write a program for them which will allow the user to input the amounts approved for each charity. The program should add up after each amount and report to the user, when the £4000 has been allocated or exceeded.

3. Write a program which asks a child to input two numbers and then work out a simple addition of those numbers. The program should read the child’s answer and as long as it is wrong, the child should be asked to try again. An appropriate message should be given when the correct answer is typed in. Try to make your program user friendly for the intended audience.

4. You are required to write program which will allow the user to type in as many positive whole numbers as they wish, and to enter a zero to indicate they have finished. Then the program should display the number of odd values and number of even values entered by the user.

Hint 1: Use an IF THEN ELSE inside the loop.

Hint 2 : Use the mod operator to work out whether the number is odd or even.

J Patterson 36

Page 37: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 5 - Arrays

So far we have been using simple data types for our variables, such as integer, string and double. In programming sometimes we may need to use data structures so that we can use and manipulate data in a more sophisticated manner. An array is an ordered collection of data items of the same data type grouped together using a single identifier (name). Each member of the array is refer to as an element. Arrays may have many dimensions but higher dimensions can get difficult to visualise and comprehend; thankfully they are not needed for AS or A-level. It is sufficient to be able to use one-dimensional arrays (sometimes known as linear lists) and two-dimensional arrays (which are sometimes known as tables).

0 1 2 3 4 The elements of the array can be referred to using a subscript. Notice that the first element starts at zero. So instead of having to declare separate variables, with an array it they can all be considered to be part of the same data structure i.e. the array. So for the above array, if we wanted it to store integers then we could declare it as follows Keyword Identifier Number of elements Keyword Keyword defining the data type of the array

Dim Number(0 to 4) As Integer

Dim Number(5) As Integer declares the same array

Subscript (or index) of the array

Hip Hip Arrays!

J Patterson 37

Page 38: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercise How would each of the following arrays be declared?

1. An array of 10 elements to store whole numbers 2. An array of 20 elements to store the price of sports items 3. An array of 100 items to store pupil surnames

One-Dimensional Arrays If we declare an array:

Dim Name(0 To 4) As String

Name(0) Dave

Name(1) Jill

Name(2) Abbey

Name(3) Kev

Name(4) Peter

We can refer to a particular element of this array:

Console.WriteLine(Name(2))

Would display the name Abbey. In general, to refer to the ith element you write Name(i)

This is really useful when combined with iteration statements:

To read in five names into the array we can write:

For i = 0 To 4 Step 1

Console.Write("Please Enter in a location " & i & ": ")

Location(i) = Console.ReadLine()

Next

Array identifier

Range of index

Array identifier

All elements of an array are of the same type

Index or subscript

J Patterson 38

Page 39: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

We can easily display these in reverse order:

For i = 4 To 0 Step -1

Console.WriteLine(Location(i))

Next

Look at the next program Module Module1 Sub Main() Dim Names(0 To 3) As String Dim index As Integer Names(0) = "Johhny" Names(1) = "Brad" Names(2) = "Idris" Names(3) = "Lenny" For index = 0 To 3 Console.WriteLine(Names(index)) Next Console.Read() End Sub End Module

We can also use a for loop to read in the names, which will save us a lot of time.

Notice that the names have been assigned into each element before using the for next loop to step through the array and write the names out to the console window.

J Patterson 39

Page 40: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Module Module1 Sub Main() Dim Names(0 To 3) As String Dim index As Integer For index = 0 To 3 Console.Write(" Please enter a name : ") Names(index) = Console.ReadLine() Next For index = 0 To 3 Console.WriteLine(Names(index)) Next Console.Read() End Sub End Module

Note : An array is a static data structure. This means that its size is defined at design time (before the program is ran) and therefore its size is fixed when the program is running. If we needed to change the size of the array, the program would need to be stopped and the code changed. Static data structures are useful in certain situations but they have limitations. Dynamic data structures can grow and shrink at run time…more on that later.

J Patterson 40

Page 41: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercises

1. Create a program that uses an array to store 5 numbers. The program should prompt the user for the 5 numbers and then write those numbers out to the screen.

2. Now adapt it further so that a running total of the elements of the array is calculated and the final total printed to the screen after the elements are listed.

3. Adapt your program in exercise 1, which gives the user the option to change the contents of an element of the array.

Parallel Arrays Another useful application of arrays is when we need to use a range of data types but they need to correspond to each other. For example, Student Name and Mark. Dim StudentName(0 to 9) As String Dim Mark( 0 to 9) As Integer We could declare two arrays and as long as the index order is adhered to, the equivalent element in one array can be used in conjunction with the data in the other array.

Index Student Name Mark 0 Fred Smith 58 1 Peter Jones 79 2 John Coles 45 3 Helen Jacobs 83 4 Susan Peters 77

4. Write a program that stores 3 students’ names and dates of birth and then

searches for a particular student and displays that student’s date of birth.

J Patterson 41

Page 42: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Two Dimensional Arrays All the arrays we have looked at so far have been one dimensional. For example : Dim SalesFigure (1 to 6) as currency This would set up an array to hold 6 elements which could hold decimal numbers formatted with £ signs. However we could actually use arrays to store data in several multi-dimensional arrays. At this level we will only need to look at 2-dimensional arrays, sometimes known as matrix arrays. Sample Code If we wanted to store a firms quarterly sales for the last 5 years. This would require the 4 quarters and the 5 years = 20 pieces of data. We could declare an array as follows :

Dim SalesFigure(4, 3) as Decimal

After running the following code SalesFigure(0, 2) = 568 SalesFigure(2, 1) = 785 SalesFigure(4, 3) = 452

F0 to 3 quarters

(4 quarters - columns)

F0 to 4 years

(5 years - rows)

J Patterson 42

Page 43: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

The array would resemble the matrix shown below.

0 1 2 3

0 568

1

2 785

3

4 452

Example

Imagine a class of 6 students that have a mini test every week for 5 weeks. The teacher records the grades in a table. A particular cell of the table is designated by student number and week number. For example:

Week Student 0 1 2 3 4

0 99 66 89 78 76 1 90 93 87 99 88 2 65 64 68 72 73 3 45 56 53 48 60 4 69 55 71 68 58 5 45 43 39 50 46

The mark for student 0 in week 1 is 66 The mark for student 3 in week 3 is 48 The mark for student 5 in week 4 is 46 The notation for specifying a cell in the table uses the row and column indices as shown below : Dim GradeTable (Row, Column) as Integer

J Patterson 43

Page 44: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

TASK Using the GradeTable array answer the following questions

1. What is contained in GradeTable(2,4)? ___________

2. What is contained in GradeTable(5,1)? ___________

3. How would you refer to the data for student 1 in week 3? ____________________________________

If you have got this far you should have noticed some key points :

• The ROW then the COLUMN is used to reference each cell

• The data type is the same, in this case it is integers being stored. (If a mix of data types is needed then that would require an array of records).Let

Let’s try coding a 2-D Array Enter the following code Module Module1 Sub Main() Dim CodeGrid(2, 2) As Integer Dim Row, Column As Integer For Row = 0 To 2 For Column = 0 To 2 Console.Write("Please enter the value for this cell ") CodeGrid(Row, Column) = Console.ReadLine

J Patterson 44

Page 45: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Next Next For Row = 0 To 2 For Column = 0 To 2 Console.WriteLine(CodeGrid(Row, Column)) Next Next Console.Read() End Sub End Module Run the program. You should be able to see that you have set up a 3 X 3 grid and therefore you will need to enter in 9 numbers into the array.

1. Write a program using a two dimensional array called SalesBoard. The array is designed to hold the sales figures of console games, for some salesmen on a market stall.

Week1 Week2 Week3 Fred 34 43 35 Dave 23 44 49 Paul 67 29 33

Initialise the sales for each person before running the program and output to the screen the sales value for each person in a grid form as shown below.

J Patterson 45

Page 46: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Enumerated Types An enumerated type defines an ordered set of values, which are generally named values (or elements/enumerators). Each value is given an ordinal value, starting at zero. Members of an enumerated type can be used as loop control variables, in case statements and as array subscripts. Enumerated types can be thought of as a new data type, a one that is designed by the programmer and they can prove to be very useful when we want to refer to something where the order is important or meaningful. They can also help programmers as a form of validation, as the “list of items” is provided in the program (so limits user error, a bit like a drop down box would). Module Module1 Dim x, y As Integer Enum Days Sun Mon Tue Wed Thu Fri Sat End Enum Sub Main() x = Days.Mon y = Days.Fri Console.WriteLine("Monday = {0}", x) Console.WriteLine("Friday = {0}", y) Console.ReadLine() End Sub

• Run the code to see how this functions.

J Patterson 46

Page 47: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

1. Write a program which defines an enumerated type for the priorities of jobs being carried out on a range of tasks in a factory. The list of priorities are given values as follows : None = 0

Trivial = 1 Standard = 2 Important = 3 Critical = 4

The program should then prompt the user for the priority number “value” of their job. Use a case statement, to report back to the user the importance of their job. This should be able to be repeated as many times as required (Hint : use a loop).

Sets A set (in computer science) is a collection of values of the same ordinal type. The values of a set have no associated order. You may recall that in maths we often use Venn Diagrams to help us explain sets.

J Patterson 47

Page 48: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Sets can be useful for looking at lists and comparing their members with other lists. Terminology

Operation Set Operator

Meaning Example

Union + Set 3 contains each value from Set1 and each value from Set2 but no duplicates

Set3 := Set1 + Set2

Difference - Set3 contains only those values from Set1 that do not exist in Set2

Set3 := Set1-Set2

Intersection * Set3 contains only those values that exist in both Set1 and Set2

Set3 := Set1 * Set2

Membership In Tests if a value is in the set…it will return a Boolean value

If 2 In Set2 Then

Look at the following code which attempts to represent the sets in the first diagram shown on page 46. Module Module1 Sub Main() Dim SetA, SetB As New ArrayList Dim InitialSet() = {1, 3, 5} SetA.AddRange(InitialSet) SetA.Add(7) SetA.Add(9) SetB.Add(6) SetB.Add(8) SetB.Add(10) If SetA.Contains(5) Then Console.WriteLine("Set A contains 5") End If If SetB.Contains(6) Then Console.WriteLine("Set B contains 6")

J Patterson 48

Page 49: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

End If If SetA.Contains(7) And SetB.Contains(7) Then Console.WriteLine("Intersection") Else Console.WriteLine("No intersection here") End If Console.ReadLine() End Sub End Module

Task • Enter and run the program above. • Adjust the program so that it shows the intersection of 7 and 9 do exist,

as shown in the diagram on page 46. • Add another set called SetC and add the values 2 and 4 to that set.

J Patterson 49

Page 50: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Extension Task We can create programs which are specially designed to handle sets. For instance in the example below we can use a special data type called IEnumerable, which is really a type of method which will loop through the enumerated list and help us determine what we need. In this case the intersection. Module Module1 Sub Main() ' Create two sets (integer arrays) Dim SetA() As Integer = {22, 33, 44, 55, 66, 77, 88, 99} Dim SetB() As Integer = {31, 38, 23, 18, 99, 55, 30} ' Find the set intersection of the two arrays Dim intersection As IEnumerable(Of Integer) = SetA.Intersect(SetB) Dim output As New System.Text.StringBuilder For Each id As Integer In intersection output.AppendLine(id) Next ' Display the output. Console.WriteLine(output.ToString) Console.Read() End Sub End Module Run the program to see it working and change the arrays to see if you can alter the output.

J Patterson 50

Page 51: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 6 Subroutines - Procedures and Functions Subroutines - These are the building blocks of programs and enable programs to consist of these self-contained routines to complete certain tasks. Procedures enable problems to be split up into modules (making them more manageable) and functions always return a value. Both procedures and functions are called (invoked) by their name (identifier) and allow the passing of parameters.

Looking at Top Down Design - it suggests that programs can be broken down into modules so that each module could perform a certain task required of that overall program.

Procedures and functions are the means by which this modular programming can be achieved.

A function or a procedure can even contain functions and procedures within itself, just like a normal program.

Functions and procedures can also have their own identifiers, their own parameters and their own local variables (i.e. just used in that module) or they can use variables which have been declared in the main program which are known as global variables.

However, it is good practice to have self-contained modules so the use of parameter passing between modules and local variables should be employed whenever possible.

Why is it a good idea to use modular programming?

• Some modules will be able to be called again and again, so we can avoid repeating code.

• Some modules will be able to be used in other programs • Modules can be tested independently and therefore facilitate error

finding and debugging • Program maintenance is easier as affected modules can be identified

and worked upon

J Patterson 51

Page 52: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

• In large projects, modules can be allocated to different programmers which will generally result in faster completion of the whole project.

Procedures

In Visual Basic there are several different types of procedure but for now we are going to concentrate on Sub Procedures. A sub-routine is a self-contained statement block that can be called from different locations in a program.

Sub procedures can be written so that they can be called from the Main Program and then subsequently executed, before returning to the main program.

Look at the following example:

Module Module1 Dim Number, Number2, Result As Integer ‘Global Variables Sub GetNumbers() ‘ procedure to get numbers from user Console.Write("Please enter a number: ") Number = Console.ReadLine Console.Write("Please enter another number: ") Number2 = Console.ReadLine End Sub Sub AddTwoNumbers() ‘procedure to add the numbers Result = Number + Number2 End Sub Sub PrintResult() ‘procedure to display results Console.Write("The result of adding " & Number & " and " & Number2 & " is " & Result) End Sub ' *******The main program starts here********** Sub Main() GetNumbers() AddTwoNumbers() PrintResult() Console.ReadLine() End Sub End Module

J Patterson 52

Page 53: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

In the above program, the program starts at the Main subroutine, which then in turn calls each procedure by its identifier.

The pseudocode for that program could be

Get two numbers to process Add the two numbers Display the result

Parameters In the code above, you will have noticed that we had to declare several global variables at the top of the program. This has been acceptable up to now but we have already said that we want to make our sub routines self-contained to make them more efficient or so we can reuse them. Public Sub CalculateAge(By Val DOB as date, ByRef Age as integer) ::::::: ::::::: End Sub Sub Main CalculateAge(Date, A) End Note : In the above procedure call DOB and Age are the formal parameters and DOB is an input parameter whereas Age is an output parameter. Also notice that the parameters in the procedure call do not have to have the same names as the formal parameters, but the order MUST be adhered to. These parameters are known as the actual parameters. As stated earlier, it is important to pass parameters as it promotes code reuse and ensures that our procedures are self-contained.

Formal Parameters

Actual Parameters

J Patterson 53

Page 54: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Enter the following program Module Module1 Private Sub CalculateArea(ByVal length As Integer, ByVal breadth As Integer) Dim Area As Decimal ‘local variable Area = length * breadth Console.WriteLine(" The area is " & Area & " m2") Console.Read() End Sub Sub Main() Dim l, b As Integer ‘local variables Console.Write(" Enter the length : ") l = Console.ReadLine() Console.Write(" Enter the breadth : ") b = Console.ReadLine() CalculateArea(l, b) End Sub End Module

• Notice that all variables are local • In this instance there is no reference parameter as the CalculateArea

procedure provided the output of the area. • We can say that parameters are passed by the subroutines

J Patterson 54

Page 55: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

The next program passes the Area back to the calling main program and it reports the area.

Module Module1 Private Sub CalculateArea(ByVal length As Integer, ByVal breadth As Integer, ByRef Area As Decimal) Area = length * breadth End Sub Sub Main() Dim l, b As Integer Dim a As Decimal Console.Write(" Enter the length : ") l = Console.ReadLine() Console.Write(" Enter the breadth : ") b = Console.ReadLine() CalculateArea(l, b, a) Console.WriteLine(" The area is " & a & " m2") Console.Read() End Sub End Module Note : to keep our exercises simple we have looked at programs in which procedures are called in order, from the main program. It should be noted however, that procedures can call other procedures, so they can be invoked from anywhere in the program by their identifier.

J Patterson 55

Page 56: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercises

1. Use a procedure to write a program to accept two integer values and test to see which is larger. If they are equal the first may be assumed to be larger. A message should be written to the screen to tell the user which is larger.

2. Prompt the user for the length and the breadth of a rectangular garden (use metres). Use a procedure to calculate the perimeter. A message should be output to the screen to inform the user.

3. Use a procedure to write a program which will calculate the gross pay for workers. The following table should help you organise how it operates. The gross pay should be passed back to the main program and displayed from there.

Input Parameters HoursWorked , PayRate

Output Parameter GrossPay

Procedure Calculate the GrossPay

Functions A function is defined as some code which carries out a well-defined task and then returns a value. A function will always return a value. Most languages have a range of built- in functions but they also allow the programmer to define their own. The Visual Basic language is particularly rich in functions to support such manipulation. For example, Console.Readline() the dot notation is used to allow the function Readline to read a line from the console.

J Patterson 56

Page 57: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

There are a whole range of string handling functions and functions to generate random numbers. (See later in the book from page 61). Visual Basic also permits the programmer to write their own functions, and these new functions, just like procedures, can then be put into a code module and called from anywhere within the program. Public Function Treble(ByVal Num as Integer) As Integer

Treble = Num * 3

End Function

ThreeTimes = Treble(Number)

Note : A function will always return a value, in this case it is an integer but can be other data types. Again the parameter names do not have to be the same but if there is more than one being passed in they should be in the correct order. The return parameter is the value the function returns.

Due to the nature of a function, it is always passing a return parameter (as it always returns a value), however it will quite often have input parameters. In the example above Num is passed into the function.

Look at the following program

Module Module1 Const Pi = 3.14 Function AreaOfCircle(ByVal R As Integer) As Double ' this function returns a double AreaOfCircle = Pi * (R ^ 2) Return AreaOfCircle

The function is called by it’s identifier and passing in the required parameter

Note : the data type of the returned value is outside the brackets. The formal parameter Num is passed in to the function

J Patterson 57

Page 58: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

End Function Sub Main() Dim Radius As Integer Console.Write("What is the radius: ") Radius = Console.ReadLine() Console.WriteLine("Returned answer from the function, the Area is: " & AreaOfCircle(Radius) & "cm squared") Console.ReadLine() End Sub End Module

Exercises

1. Use functions to write a program to calculate the surface area and volume of a sphere with the radius (in cm) given as input. The required formulae are:

i. surface area := 4 * Pi * radius * radius; ii. volume := 4/3 * Pi * radius * radius;

2. Use functions to write a program to convert degrees Fahrenheit into degrees centigrade and vice versa. Formulae are:

CtoF := (C * (9/5)) + 32;

FtoC := (F - 32) * (5/9);

This is the function call, using the

identifier

J Patterson 58

Page 59: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Consolidation Task

You are required to write a program for a local gym which will inform the user if they are overweight. The program should display an appropriate message to the user, giving an introduction to what the program does.

You will need two functions to read in the person’s height in meters and their weight in kilograms.

You will also need to use a function to calculate the body mass index for that person, which uses the equation BMI = Weight / Height 2

Once you have the BMI, pass that value to another function which should return the appropriate message about the person’s weight. This should be based on the following information:

19 or less they are underweight and should eat more 20 – 25 they are fine and should continue as normal 26 – 30 they are slightly overweight, start to exercise and modify diet 31- 40 you will need to lose weight 41 or more, you have a serious weight problem, see a doctor

Extension Task

Most people are used to entering their weight in stones and lbs, and their height in feet and inches in the UK. Adapt your program so that it allows the user to enter their weight and height in imperial units, you can then use these units to calculate the BMI correctly. You may need to look up the correct conversion. Alternatively you could convert back to metric to use your existing function. You could even allow your program to enable your users to calculate BMI in metric or imperial i.e. give them the choice. NOTE : Remember it is fine to call a function from another function.

J Patterson 59

Page 60: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Built in Functions

VB has a number of very useful built in functions to help us to carry out a huge range of useful tasks. It is important that we can manipulate strings and therefore we need to learn a range of functions which can help us with strings.

String Handling Functions

Function Variable(s) Data Returned

Description

Length MyString: String Integer Returns the number of characters in string MyString

Substring MainString : String

Sub: String

Pos: Integer

String Returns a substring from the main string, and the position in the main string needs to be stated

IndexOf MyString: String

Sub: String

Integer Returns the position of the first character in substring Sub that occurs in the string MyString

ToUpper MyString: String String Returns a copy of string MyString in upper case

ToLower MyString: String String Converts string MyString to lower case

Task : Run the following program and try changing

• The string • The values in brackets used to extract characters and substrings

J Patterson 60

Page 61: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Module Module1 Sub Main() Dim MyString, SubString As String Dim OneChar As Char Dim Len As Integer MyString = "The cat sat" 'Extracting one character OneChar = MyString.Substring(2) Console.WriteLine(OneChar) 'Extracting a substring SubString = MyString.Substring(1, 6) Console.WriteLine(SubString) 'Finding the length of the string Len = MyString.Length Console.WriteLine("The length of your string is " & Len & " characters") Console.Read() End Sub End Module Exercises 1 – Counting the words Write a program which asks the user to type in a sentence into a string variable. You should then write a subroutine which will count the number of words in the sentence. Hint : You will need to think about how many spaces are in the string. Use the Substring function to look at each character and test if it a space. Using for loops based on the length of the string is also a great way to process the individual characters of a string.

J Patterson 61

Page 62: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Extension Ex 2 - Palindrome Write a program which asks the user to enter a string, and then you should check to see if the string is a palindrome. (A palindrome is a word that is the same forward as it is backwards, such as level, abba, kayak, civic). You should then give the user a message telling them whether or not their word is a palindrome. Test Data: Develop your own test data for this program, you have some palindromes which will be normal, valid data but you need to come up with some invalid and erroneous values to fully test your code. Hint : You can use the length function to calculate the length of the string and use that to set the rear position. Position one is the front of the string and you can then use the Substring function to extract characters and compare front and rear.

Using the Rnd() Function to Generate Random Numbers We often want to simulate events where random numbers occur, such as throwing a die. Computers cannot produce truly random numbers but Visual Basic like most high-level languages, provides us with a pseudo-random number generator to get over this problem. The built in function Rnd() will allow us to generate a number between 0 and 1. Look at the following statement :

R = Int(Rnd() * 10) + 1 It returns an integer between 0 and 10 because we have added 1 and multiplied by 10 to give our range. When you initialise the random number generator it uses an integer obtained from the system clock, so it helps simulate randomness but there can be some repetition. To prevent this from happening (the compiler will use a different value each time), you can add the statement Randomize() before you want to use the random function.

J Patterson 62

Page 63: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercises 1. Guess the number game.

Prior Knowledge Required How to generate random numbers IF statements Loops and how to increment. Write a program whereby the computer selects a random number between 1 and 20. Use the Rnd() function to generate the number. The user keeps guessing which number the computer has chosen until they get it right. The computer should respond with ‘you guessed it’ or ‘too high’ or ‘too low’ after each guess. After the user has guessed the number the computer should tell them how many attempts they have made.

2. Make a game of rock, paper scissors against the computer.

Prior Knowledge Required Nested If’s using logical operators Loops How to generate random numbers

Algorithm Design Ask the user to enter either rock, paper or scissors Get the response Generate a random number from 1 to 3 (1=rock, 2=paper, 3=scissors) Compare user selection and computer selection Display a message as to who wins.

Extension Make sure the user enters a valid entry. (The input must be a number must be between 1 and 3 and nothing else). Add a loop structure to play several times and keep a running score.

J Patterson 63

Page 64: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

3. Write a program that will generate a random playing card e.g. ‘5 Hearts’,

‘Queen Clubs’ when the return key is pressed.

Prior Knowledge Required IF’s with logical operators Random Number Generator Rather than generate a random number from 1 to 52. Create two random numbers – one for the suit and one for the card. Extension Make a loop structure so playing cards can keep being generated.

J Patterson 64

Page 65: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Records

A record can be classed as a user defined data type. It is a structured type which is created by the user. A record is a collection of variables, which can be of different data types and there is no need to adhere to any particular order (unlike a 2-D array). The variables used can be regarded as the fields of the record structure. In order to use records we need to define what type of record we want, that is, what fields our record is going to have and what type of data we are going to store in them.

The syntax of a record type declaration is:

Structure Identifier = record

Dim Field1 As Type1

Dim Field2 As Type2

.. ..

Dim Field10 As Type5

End Structure {of record type declaration}

It is good practice to declare Type declarations as global declarations. Once the new user defined type is declared we can declare variables of this new type in our programs, just as we declared variables using the built in data types such as Integer and String. Look at the following example for a small Christmas savings club: Account No Forename Surname Balance (£) 3456 Steven Jobis 58 5632 William Gatis 35 3267 Marcus Zuckerburger 73 4499 Jeanette Winger 96

One record

J Patterson 65

Page 66: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

The above table shows that we can store records about the club. We have four fields and all the items about each customer are stored in one record. In order to start storing these records, we need to define a record structure.

Structure SavingsType ‘this declares the data type for one record Dim AccountNo As Integer ‘declare the fields needed Dim Forename As String Dim Surname As String Dim Balance As Decimal End Structure Dim Saver as SavingsType ‘declare a variable to hold one record

Arrays of Records If we now want to use the record structure we can use an array Dim Savers(0 to 99) as SavingsType ‘ an array of records with space for 100 records NOTE : the identifier SavingsType could have been simply just Savings, however it is good practice to use the word Type so that you can easily identify a user defined type in your code. Look at the following program Module Module1 Structure SavingsType ‘this declares the data type for one record Dim AccountNo As Integer 'declare the fields needed Dim Forename As String Dim Surname As String

J Patterson 66

Page 67: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Dim Balance As Decimal End Structure Dim Savers(0 To 3) As SavingsType 'declares an array of four records Sub Main() 'initilise record 0 Savers(0).AccountNo = 3456 Savers(0).Balance = 58 Savers(0).Forename = "Steven" Savers(0).Surname = "Jobis" Console.WriteLine("Account No :" & Savers(0).AccountNo) Console.WriteLine("Name : " & Savers(0).Forename & " " & Savers(0).Surname) Console.WriteLine("Balance: £" & Savers(0).Balance) Console.Read() End Sub End Module Notice :

• The record structure is declared in the module- that way it can be used anywhere in the program

• The dot notation which can be used to refer to the fields of the record Savers(0).Forename = "Steven" We should try to make our programs more efficient and as usual for processing an array we can use a for loop. TASK Run the next program to process the array of records first shown above about savings accounts. Use the data from the table on page 65.

Array identifier Array Subscript

Field

Data

J Patterson 67

Page 68: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Module Module1 Structure SavingsType Dim AccountNo As Integer Dim Forename As String Dim Surname As String Dim Balance As Decimal End Structure Dim Savers(0 To 3) As SavingsType 'declares an array of four records Sub Main() Dim index As Integer For index = 0 To 3 Console.Write("Please enter the account number: ") Savers(index).AccountNo = Console.ReadLine 'reads in values from the user Console.Write("Please enter the account balance : ") Savers(index).Balance = Console.ReadLine Console.Write("Please enter the forename : ") Savers(index).Forename = Console.ReadLine Console.Write("Please enter the surname : ") Savers(index).Surname = Console.ReadLine Console.WriteLine() Next For index = 0 To 3 Console.WriteLine("Account No :" & Savers(index).AccountNo) Console.WriteLine("Name : " & Savers(index).Forename & " " & Savers(index).Surname) Console.WriteLine("Balance: £" & Savers(index).Balance) Console.WriteLine() Next Console.Read() End Sub

J Patterson 68

Page 69: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

End Module Extension Task Adapt the program so that the output resembles the table on page 63. Exercise

1. Create a program which creates a record for pupils who have completed an exam. The fields being stored are Forename, Surname, DateOfBirth and FinalScore.

• Create an array for ten pupils and read in the details from the user.

• Calculate the average FinalScore and output this to the console window.

Extension

2. Adapt your program to display the names of the pupils who achieved the highest and lowest marks.

J Patterson 69

Page 70: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Files In all of our programs so far, we have not stored any data for future use and when the program is closed, any data has been lost. This may have struck you as a bit of a waste when we have generated lots of data in our arrays and arrays of records. In reality we know that it is important to be able to store data permanently and retrieve it, change it and even delete it when required. The solution to this is to store data in a File. Visual Basic allows us to store data in several ways the most common of which are :

• Text Files • Random Access Files

In order to understand how files function, it is important to understand the basics of File Organisation. File Organisation Data can be in retrieved and held in different ways. This is useful in that we often wish to store and retrieve data in such a way that suits our purpose (ie. the application). Serial Files In a serial file the data is held in the order in which it arrives ie. not in any logical order. This means that the only way that the data can be accessed is by reading through the data from the start until the required item is found.

J Patterson 70

Page 71: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Sequential files In a sequential file the data is sorted into some kind of order. In order to access a record from the file we must know the entry for at least one field (the key). Clearly a sequential file may only be sequential on one field and so the KEY must be chosen carefully. This is usually something sensible, for example in a file of student records the key might be StudentNumber.

Note: You cannot just delete a record in a serial or sequential file. You need to copy all the records to a new file, omitting the record you want to delete. Also you cannot insert a record in a serial or sequential file. You need to copy records from the original file to a new file, inserting the new record in the correct place in the new file. The main drawbacks with serial and sequential files is that they can prove quite slow. You must start a search for a record from the beginning of the file, and possibly all the way through the file, if the record you are looking for is the last one or not in the file at all. Adding or deleting records means writing all the records to a new file. This can take some considerable time for a large number of records. Random access files (also known as direct access files) do not store records one after the other but each record is stored at an address (or position relative to the start of the file) calculated from the value of its key field. This means a record can be independently accessed using its address. Visual Basic will allow

J Patterson 71

Page 72: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

us to set up fixed-length records, so we can update in situ (overwrite an existing record with an updated record) without disrupting the file. Random Files A random file is probably more typical of what we are used to. The term 'random' does not mean that the data is held in a random order but that an individual item of data can be chosen at random and accessed straight away. In order to be able to do this we need to know how to locate area on the storage medium which contains the data item. With a random file the address will be calculated using an ADDRESS GENERATING ALGORITHM or HASHING ALGORITHM. This algorithm will take the key and process it according to some predetermined mathematical formulae to produce an address. Clearly this means that a record can only be accessed randomly if we know its key, and also that there can only be one key. There are some problems associated with this too, but we will look at this more closely at A2 level.

J Patterson 72

Page 73: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

How to use a file:

• Open file FileOpen (<num>,<path>,<OpenMode>) • Read from the file: LineInput(<num>) • Or write to the file: Write or WriteLine (<num>, <string>)

Print or Printline (<num>, <string>) • Close the file: FileClose (<num>)

Note : In file handling when we are reading a file, we are reading it into memory and when we are writing a file we are writing from memory to the storage medium.

Text Files

A text file represents a serial file containing a sequence of characters, represented by their ASCII/Unicode codes. A text file can be opened and read in a text editor like notepad.

File Names

In VB when opening a file it is vital to supply the file’s name and let the program know where the file is located. This can be carried out by several methods :

1. Hardcoding the full path and file name 2. Using the CurDir (Current Directory) Function 3. Using the OpenFileDialog control 4. Using the default bin folder

Task Make a folder on your area or portable device called SavingsClub. You need to obtain the text file Savings from the network (or quickly create your own in notepad- using the savings club data on page 65).

J Patterson 73

Page 74: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Now enter the following code. Module Module1 Sub LoadAndDisplaySavings() Dim Count As Integer 'to count through the records Dim Saver As String 'a string to hold the contents of each record FileOpen(1, "Savings.txt", OpenMode.Input) 'open the file to read in Count = 1 While Not EOF(1) ‘EOF – is End Of File Saver = (LineInput(1)) ' assigns the record to Saver Console.Write(Saver) Count = Count + 1 'increment the record number Console.WriteLine() End While Console.Read() FileClose(1) End Sub Sub Main() LoadAndDisplaySavings() End Sub End Module In order to be able to run the program VB needs to access the text file. Place the text file Savings in the bin debug folder for your program. Now run the program. Notice how the program is accessing a text file that had already been created and it reads in one line at a time using the LineInput command. Now we have grasped the basics of file handling with a basic text file, we need to consider what else we need to be able to do with the file.

Common tasks include:

• Creating the file through VB/writing to the file

J Patterson 74

Page 75: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

• Appending records/items to the file • Searching for an Item/record • Deleting an item/record

The Sweet Shop Text File The following program has a procedure to carry out each of the above tasks. Make sure you understand each procedure and then create the final program and run it using the instructions provided. Task 1

You are going to create a text file to hold confectionary items called sweets.txt. This file does not exist but when you run the code below, save the program in an appropriate folder, once you run the program, enter the following data.

Mars Bar, Bounty, Milky Way, Wispa This will create the text file, in the bin debug area of your saved program. Note

• the use of the CurDir() function. This tells VB.Net where the file is located.

• The use of OpenMode.Output is the code used when we need to “write” to the file but if the file does not exist it will create it.

• The use of PrintLine actually writes to the file.

Module Module1 Sub WriteFile() Dim Confectionary As String Dim Filename As String Filename = CurDir() & "\sweets.txt" 'use of CurDir() FileOpen(1, Filename, OpenMode.Output) 'if file does not 'exist OpenMode.Output creates it Console.WriteLine("Please enter a confectionary item") Confectionary = Console.ReadLine

J Patterson 75

Page 76: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Do While Confectionary <> "Q" PrintLine(1, Confectionary) Console.WriteLine("Please enter a confectionary item") Confectionary = Console.ReadLine Loop FileClose(1) Console.ReadLine() End Sub Sub Main() WriteFile() End Sub End Module Your text file should look something like the following

Task 2 Now we want to append to the file, let’s add Twirl and Twix. Change the line in your program that says FileOpen(1, Filename, OpenMode.Output) to FileOpen(1, Filename, OpenMode.Append) Run the program and add the new data, the file should now look like

J Patterson 76

Page 77: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Task 3 - Searching the file - Linear Search If we want to locate an item in a text file then we will have to go through the file, one line at a time until we find the item we are looking for. If the item does not exist we will have to until the end of the file. Note the use of the Boolean variable Found to assist with this. Module Module1 Sub SearchFile() Dim Confectionary As String Dim Filename As String Dim Confect As String Dim Found As Boolean Filename = CurDir() & "\sweets.txt" 'use of CurDir() Console.WriteLine("Please enter the confectionary item you require...Q to quit") Confect = Console.ReadLine 'user inputs an item to search FileOpen(1, Filename, OpenMode.Input) ' Found = False Do While Found = False And Not EOF(1) Confectionary = LineInput(1) If Confectionary = Confect Then 'looking for a match Found = True Else Found = False End If Loop If Found = True Then Console.Write("It is in the file you were hungry for " & Confectionary) Else Console.Write("Not in the file") End If Console.Read() FileClose(1) Console.ReadLine() End Sub Sub Main() SearchFile() End Sub End Module

J Patterson 77

Page 78: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Task 4 The final task is to be able to delete an item from the file. This is probably the trickiest task but we now know what to do to find the item to delete. Yes, we can use the linear search. Remember what we said earlier, to delete an item we need to copy all of the items to a new file, except the item that we want to delete. Notice in this program there are two procedures, one to delete the file and another to display the text file so you can check your deletions are working. Module Module1 Sub DeleteItem() Dim NewFile As String Dim OldFile As String Dim DeleteConfect As String Dim FindConfect As String NewFile = CurDir() & "\sweets2.txt" 'a new file OldFile = CurDir() & "\sweets.txt" ' the current file Console.Write("Please enter the confectionary item you wish to delete ") DeleteConfect = Console.ReadLine() FileOpen(1, OldFile, OpenMode.Input) 'open to read in FileOpen(2, NewFile, OpenMode.Output) 'open to write to Do FindConfect = LineInput(1) If FindConfect <> DeleteConfect Then 'if not what needs deleted then copy across to new file PrintLine(2, FindConfect) End If Loop Until EOF(1) FileClose(1) FileClose(2) Console.ReadLine() Kill(OldFile) 'deletes the old file My.Computer.FileSystem.RenameFile("sweets2.txt", "sweets.txt") 'renames the new file back to the oldname End Sub

J Patterson 78

Page 79: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Sub DisplayFile() Dim Confect As String FileOpen(1, "sweets.txt", OpenMode.Input) 'open the file to read in While Not EOF(1) Confect = (LineInput(1)) ' assigns the record to Saver Console.Write(Confect) Console.WriteLine() End While Console.Read() FileClose(1) End Sub Sub Main() DeleteItem() DisplayFile() End Sub End Module Run the program but ensure that you start off with the sweets text file in the Bin Debug folder of your program. You do not need to create sweets2 as the program will do that for you. Note

• The use of the Kill function to delete the old file. • The use of RenameFile command which allows us to rename the file so

we are ready for a new deletion. (Adding a loop to the program would enable this).

J Patterson 79

Page 80: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Exercise - Text Files

Potions Task

You have been given the task of writing a program for Professor Snipe to manage the potions he has been making at Hogwerts. He would like you to manage his file of potions which he has created in notepad as a simple text file. He has left the file on the common drive in a folder called Potions Task. If you cannot locate this file you could recreate it using the screen shot below.

He would like to be able to do the following with the new program:

• Append new potions to the end of the file • Read in the whole file of potions and display them in the console

window • Search for an individual potion in the file • Delete any potions from the text file that have been used up

NOTE : Each task will need to be in a separate procedure and it is important that the user can repeat tasks so you may want to give them a menu. (Hint: a select case and a loop would be able to provide these things).

J Patterson 80

Page 81: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Chapter 10 - Windows Form Applications Start a new project but this time choose a Form Application

You will then see the following screen

Some items will look familiar and others are new. The Form This is your working area. This is where you can design an interface which the user can interact with, you can do this by adding controls (objects). When you double click on a form you go to the coding window, which will look quite familiar as it is where we can write programs based on the controls. Solution Explorer This displays the components of you “solution” or group of files/projects that you have created in order to solve a problem. Notice in the problem above the solution contains the project file and the form.

Solution Explorer

Properties Window

Toolbox

Form

J Patterson 81

Page 82: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

ToolBox This contains icons for each control you can place on a form. These controls have certain categories, based on what they are used for but the ones we will focus on are Windows Forms Common Controls. The Properties Window When you place a control from the toolbox onto the form you will create an object. In fact the form itself is an object. All objects have properties (or attributes) and these are what are listed in the properties window. We can change many of these properties and at design time can change them in the properties window. An example Object : Button Properties : Height, Width, Color etc Task Let’s try creating our fist program using a form.

• Drag a button from the toolbox onto your form and then drag a label • Click on the button, so it is selected, then go to the properties window • Properties are listed alphabetically so go down to Text • Change the right hand column to “Press Me” and you will

see that this also changes on the object on the form. • Double click on the button and go through to the code

window…you will see a screen as shown below

• Notice there is a procedure already created to deal with when the button is clicked. This procedure is known as an “Event Procedure” as it is triggered (invoked) by an event happening to the object, in this case click.

J Patterson 82

Page 83: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

• Type in the procedure Label1.Text = "Hello World"

• Now run the program and press the button. Congratulations, you can now use windows form applications too. Exercises

1. Try playing around with the controls on your form to find out what they do. Many of the objects you create will be familiar to you based on your experience of using windows.

2. Write a program, which contains two buttons, one with the text “STOP” and one with the text “GO”. When the GO button is pressed a label should appear saying “START” in green, when the STOP button is pressed the label should change to say FINISH in red.

Hint : to change colour of label use Label1.ForeColor = Color.Green

Now let us think some more about the properties of objects. Task Create a new project and add a button and a label. Set the following properties and note the use of abbreviations and conventions on control names. (This makes your code more readable).

Object Property Value/Setting Button Name cmdPress Button Text Press Me Label1 Name lblMessage Label1 Text Blank Label1 Font Size 16, Bold

J Patterson 83

Page 84: Programming using Visual Basic Express€¦ · Visual Basic itself has gone through a lot of transformations and the latest version is VB 2012. Event driven and object oriented, Visual

Visual Basic Express

Now we are ready to add some code so, double click on the button and add the following in the event procedure Public Class Form1 Private Sub cmdPress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPress.Click MessageBox.Show("Hello There") lblMessage.Text = "Ouch that hurt!!" End Sub End Class Run the program and click on the button. Reply to the message box that appears by clicking OK and then the label text will appear. This shows sequence at work.

J Patterson 84


Recommended