VB Guide Introduction to Programming in Visual asic to Programming in Visual asic Contents 1. First...
Transcript of VB Guide Introduction to Programming in Visual asic to Programming in Visual asic Contents 1. First...
GCSE Computer Science – VB Guide
1
Introduction to Programming in Visual Basic
Contents
1. First Programs ........................................................................................................................................................... 3
a. Hello World ........................................................................................................................................................... 3
b. Hello Fred .............................................................................................................................................................. 4
c. Hello with properties ............................................................................................................................................ 4
The Basic Rules .................................................................................................................................................................. 5
Variables............................................................................................................................................................................ 5
Keywords ........................................................................................................................................................................... 6
2. Arithmetic ................................................................................................................................................................. 7
a. Addition ................................................................................................................................................................. 7
b. Adding machine .................................................................................................................................................... 7
c. Calculation Machine.............................................................................................................................................. 7
d. Order of Operations / BIDMAS ............................................................................................................................. 8
e. Exponentiation ^ ................................................................................................................................................... 8
f. Remainder (Modulus) ........................................................................................................................................... 8
g. Integer division (DIV)............................................................................................................................................. 9
3. Math related methods ............................................................................................................................................ 10
a. Absolute value..................................................................................................................................................... 10
b. Square root ......................................................................................................................................................... 10
c. Round .................................................................................................................................................................. 10
d. Area and circumference of a circle ..................................................................................................................... 10
4. Comments & Whitespace ....................................................................................................................................... 11
a. Add comments and whitespace to your code .................................................................................................... 11
5. Selection .................................................................................................................................................................. 12
Comparison Operators ................................................................................................................................................ 12
Logical Operators ........................................................................................................................................................ 12
b. If … Else ............................................................................................................................................................... 13
c. If… ........................................................................................................................................................................ 14
d. If…ElseIf … Else .................................................................................................................................................... 14
e. Calculation Machine - Extension ......................................................................................................................... 15
f. Grade Calculator ................................................................................................................................................. 15
g. Nested Selection ................................................................................................................................................. 16
h. Case Statement ................................................................................................................................................... 17
i. Food Selection ..................................................................................................................................................... 18
6. Count controlled loop… - For…Next ........................................................................................................................ 19
GCSE Computer Science – VB Guide
2
a. Counting .............................................................................................................................................................. 19
b. Potato count ....................................................................................................................................................... 20
c. Count in 2s .......................................................................................................................................................... 20
d. Countdown .......................................................................................................................................................... 20
e. Timetable challenge ............................................................................................................................................ 20
7. Condition controlled loops… - Do While…Loop ...................................................................................................... 21
a. Counting version 2 .............................................................................................................................................. 21
b. Countdown version 2 .......................................................................................................................................... 21
c. Squared values .................................................................................................................................................... 22
d. Bike depreciation – Using Boolean flag .............................................................................................................. 22
e. Guess the number ............................................................................................................................................... 23
8. Condition controlled loops… - Repeat…Until .......................................................................................................... 23
a. Counting version 3 .............................................................................................................................................. 23
b. Timetable quiz ..................................................................................................................................................... 24
9. Arrays ...................................................................................................................................................................... 25
a. Creating Array ..................................................................................................................................................... 25
b. Stored Sports Array ............................................................................................................................................. 25
c. Investigate and Manipulate a Sports Array ........................................................................................................ 26
GCSE Computer Science – VB Guide
3
1. First Programs a. Hello World The first program you will write consists of two statements. The first statement tells the computer to write a line of
text which is Hello World! into the Console application. The second statement’s sole purpose is to prevent the
application from running so quickly that you might miss it. To check it, delete the line 5 and execute the program
again.
Flowchart Pseudo code VB code
1 Module Module1 2 3 Sub Main() 4 Console.WriteLine("Hello World") 5 Console.ReadLine() 6 End Sub 7 8 End Module
Save the file as 1a HelloWorld.sb, then press the play button or F5 to run it.
The first statement tells the computer to write a line of text which is Hello World! into the console application. The
second statement’s sole purpose is to prevent the application from running so quickly that you might miss it. To
check it, delete the line 5 and execute the program again.
The black window that appears when you run the program is the console application. It is where the result of this
program goes. Console in our program is called an object. A console application is one which the user interacts with
the application by running it from the Windows Command – prompt window and then typing in commands as directs
by the application.
Line by line analysis Line 1 & 8 start and end of the entire program
Line 3 & 6 start and end or the Main procedure (subroutine), which is the first code to run when your
application is loaded
Line 4 calls the WriteLine method of the Console class, outputting the argument ‘Hello World’ on the
screen
Line 5 calls the ReadLine method of the Console class, waiting for an input from the user
OUTPUT “Hello World”
GCSE Computer Science – VB Guide
4
b. Hello Fred To make the program that is a bit more interactive we need to introduce variables.
Flowchart Pseudo code VB code
1 Module Module1 2 Dim strName As String = “” 3 4 Sub Main() 5 Console.WriteLine("What's your name?") 6 strName = Console.ReadLine() 7 Console.WriteLine("Hi " & strName) 8 Console.ReadLine() 9 End Sub 10 11 End Module
Line by line analysis* Line 2 declares a string variable called strName and assigns a value of an empty string
Line 5 outputs ‘What’s your name?’ in the console application
Line 6 waits to take an input from user and stores it in the strName variable
Line 7 outputs the line ‘Hi Fred’ in the console application, the & joins (concatenates) both of the stings
Save the file as 1bHelloFred.vb and to run it.
c. Hello with properties Edit the program above to add a title and to change the text colour.
1 Module Module1
2 Dim strName As String
3
4 Sub Main()
5 Console.Title = "Welcome Message"
6
7 Console.WriteLine("What's your name?")
8 strName = Console.ReadLine()
9
10 Console.ForegroundColor = ConsoleColor.Cyan
11 Console.WriteLine("Hi " & strName)
12 Console.ReadLine()
13 End Sub
14
15 End Module Line by line analysis Line 5 sets the title property of the console application
Line 10 sets the text colour property in the console application
Save the file as 1c HelloColour.vb and to run it.
strName = ””
INPUT strName
OUTPUT strName
It is important to get the sequence of
the instructions right, to make the
program do what you want it to do.
GCSE Computer Science – VB Guide
5
The Basic Rules To set an object property, we use this ‘dot’ convention:
ClassName.PropertyName = PropertyValue
where ClassName is the class, PropertyName the property and PropertyValue the value you want to establish.
To invoke a class method, use this convention:
ClassName.MethodName(MethodInputs)
where ClassName is the class, MethodName the method and MethodInputs the inputs needed by the method.
Variables ‘Variables’ are another of the most fundamental concepts in computer programming.
• A variable is a space in a computer’s memory where we can hold information used by our program – just like
storing things in a box.
• Once a variable is created, the information stored inside it can be set or changed.
• Another word for changing is ‘varying’ – hence the word variable.
Here are three key principles for using variables:
a. Always give a variable a sensible name
A variable must have a name that’s easy to understand and tells us what kind of information it stores – just like putting a label on the box to tell us what’s inside.
Variable names should never contain spaces
Variable names should use CamelCaps to mix upper & lower case.
Variable names should start with three letters as a ‘prefix’ to indicate what type of data they
contain:
Prefix Short For Meaning Example
int integer Variable stores a whole number intTestMark
str string Variable stores any kind of characters strFullName
boo boolean Variable stores either ‘true’ or ‘false’ booValidReply
dbl double Variable stores a decimal number dblPriceApple
dte date Variable stores a date dteMyBirthday
b. Always ‘initialise’ a variable
Variables should always be given a starting value. Another word for ‘start’ is ‘initial’, so this process is called initialising a variable. For example, at the start of a game, an example of initialisation might be intScore = 0
c. Learn to use the terms ‘define’, ‘assign’ and ‘value’
‘Value’ is the term used for a piece of information stored in a variable.
‘Assign’ is the technical term for putting a value in a variable.
‘Declare’ is the term used for when we declare variables to ensure that a space is reserved in memory
For example, “I am going to assign the value 500 to the variable called intScore”
And as a piece of code, that line would translate as - intScore = 500
GCSE Computer Science – VB Guide
6
For example, “I am declaring a variable called strName to with a string data type” -
And as a piece of code, that line would translate as - Dim strName As String
The Dim part of this statement allocates space in memory to store the variable.
Keywords All words in blue are VB Keywords and must be typed correctly. Keywords are ‘reserved’, which means you cannot
use them as names for variables or procedures. Below are a few keywords but there are many more.
String Integer Decimal As If Then Else Sub For Case True False While = * > And Or
GCSE Computer Science – VB Guide
7
2. Arithmetic There are seven different arithmetic operations on numbers that you need to know:
+ - * / ^ \ Mod
Next you will practice all of them in task a-g.
a. Addition Now create the program below where we will add values stored in variables. Here we are using variables type
integer. An integer is used to represent whole, non-decimal numbers. Examples of such numbers are:
1 -20 4000
When we create a variable to store an integer we use int as the prefix for the variable name.
Flowchart Pseudo code VB code
1 Module Module1 2 Dim intNum1 As Integer = 5 3 Dim intNum2 As Integer = 4 4 Dim intTotal As Integer 5 6 Sub Main() 7 intTotal = intNum1 + intNum2 8 Console.WriteLine("The total is " & intTotal) 9 Console.ReadLine() 10 End Sub 11 12 End Module
Save the file as 2a Adding_v1.vb and run it.
b. Adding machine Edit the addition program so it takes two input values and output the result of the calculation.
Save it as 3a AdditionMachine_v1.vb
c. Calculation Machine Repeat the last program, but this time make it also subtract, multiply and divide the two numbers. Note that you
need to store the result of the division as a Double data type. Save it as 2c calculationMachine_v1.sb and test that it
works.
intNum1 = 0
intNum2 = 0
intTotal = 0
INPUT intNum1
INPUT intNum2
intTotal = intNum1 + intNum2
OUTPUT intTotal
GCSE Computer Science – VB Guide
8
d. Order of Operations / BIDMAS a) Try writing a program that will take a number, multiply it by
three and then add four.
b) Try writing a program that will take a number, add four and then
multiply by three.
Put the number 7 into both programs and check that they work correctly.
Save it as 2d BIDMAS_v1.sb and test that it works.
e. Exponentiation ^ The exponent of a number says how many times to use the number in a multiplication.
Exponents are also called powers or indices. Write a program that calculates the result of two
inputs, one for the base and one for the exponent.
Save it as 2e exponentiation_v1.sb and test that it works.
f. Remainder (Modulus) To calculate the remainder the Mod operator is used. This operator returns the remainder after a
division. Write a program that takes two inputs, one for the dividend and one for the divisor.
Save it as 2f remainder_v1.sb and test that it works.
D M A S I B
( ) x2 ÷ x + -
84
exponent (or index or power)
base
GCSE Computer Science – VB Guide
9
g. Integer division (DIV) To calculate integer division the \ operator be used in VB. It works like normal division but returns
the whole number of times one number goes into the other e.g. 13 \ 3 = 4. Again, write a program
that takes two inputs, one for the dividend and one for the divisor.
Save it as 2f integerDivision_v1.sb and test that it works.
GCSE Computer Science – VB Guide
10
3. Math related methods The Math class provides you with lots methods to allow common mathematical functions. In this chapter you will
use the absolute, square root, and round, but there are many more you could use.
variableName = ClassName.MethodName(MethodInputs)
a. Absolute value Use the absolute value method. In math, the absolute value is the positive part of a number and it looks like this:
Math.Abs(argument)
where the argument is the number we want the absolute value of.
Make a program that asks user for a number. The program should then return the absolute value of that number.
Store the values in two separate variables.
The result should look like this.
Save it as 3a absolute_v1.sb and test that it works with the following values 7, -12.
b. Square root Repeat the last program, but this time make it give the square root of a numbers.
Math.Sqrt(Argument)
Save it as 3b squareRoot_v1.sb and test that it works with the following values 4, 25. The value must be a non-
negative number.
c. Round Repeat the last program, but this time make it take an input from the user and then round it. The round method can
take one or two arguments.
Math.Round([number to be rounded]) OR Math.Round([number to be rounded], [number of decimal places])
Math.Round(2.555) will give you 3 OR Math.Round(2.555, 2) will give you 2.56
Save it as 3c round_v1.sb and test that it works with the following values 2.5555, 45.346.
d. Area and circumference of a circle Create a program where you ask the user for the radius of a circle. Your program should then calculate the area and
circumference. The area and circumference needs to be rounded to two decimal places.
HINT: use Math.PI
GCSE Computer Science – VB Guide
11
4. Comments & Whitespace Comments are bits of text in the program code that aren’t used by the computer, but help to explain what is going
on. They are there to make your code more readable and understandable. You can write comments using an
‘ apostrophe.
There are three types of comments:
a) Program header
When creating programs it is a good idea to always put a comment at the top of your small basic programs to give some idea of what your program does and who wrote it, when it was written, and the version of the program. This is known as a program header
b) Simple comment
You can include a comment above a line of code explaining what the section or part does.
c) Inline comment
You can include a comment at the end of a line of code but NOT at the start.
Comments make it MUCH easier to see what you have done when you come back to your code several months later
and you should use them regularly.
Whitespace is used in the layout of your code to make the code more readable and to section out different parts.
a. Add comments and whitespace to your code Go back and add code to the Area and Circumference of a Circle task and add comments and whitespace to the
code.
1 ' Round program 2 ' by Joe Bloggs 3 ' 18/10/2016 4 ' version 1 5 6 Module Module1 7 8 'declaration and initialising of required variables 9 Dim dblRadius As Double = 0 0 Dim dblArea As Double = 0 11 Dim dblCircumference As Double = 0 12 13 Sub Main() 14 15 'asking user for radius and storing input in dblRadius variable 16 Console.Write("Enter the circle's radius: ") 17 dblRadius = Console.ReadLine() 18 19 'storing the result of the area calculation in dblArea variable 20 dblArea = Math.PI * dblRadius ^ 2 21 dblArea = Math.Round(dblArea, 2) 'rounds the area to 2 decimal places 22 23 'storing the result of the circumference calculation in dblCircumference variable 24 dblCircumference = Math.PI * dblRadius * 2 25 dblCircumference = Math.Round(dblCircumference, 2) 'rounds the circumference to 2 decimal places 26 27 'displays the area and circumference 28 Console.WriteLine("The circle's area is " & dblArea) 29 Console.WriteLine("The circle's circumference is " & dblCircumference) 30 31 Console.ReadLine() 'ReadLine used to pause the console window 32 33 End Sub 34 35 End Module
GCSE Computer Science – VB Guide
12
5. Selection Selection means selecting (or choosing) what to do next. Should I
cycle to school, or ask for a lift? If it’s a sunny day I might cycle.
If it’s raining, I’ll ask for a lift.
Comparison Operators Comparison operators compare two values, with the output
of the comparison being true or false.
Comparison Result
equal to (6 = 7) false
(4 = 4) true
not equal to (6 <> 7) true
(4 <> 4) false Comparison Result
greater than (8 > 3) true greater than or equal to (8 >= 3) true
(6 > 7) false (6 >= 7) false
(4 > 4) false (4 >= 4) true
less than (8 < 3) false less than or equal to (8 <= 3) false
(6 < 7) true (6 <= 7) true
(4 > 4) false (4 <= 4) true
Logical Operators Logical operators are used to combine logical expressions build using comparison operators. Visual Basic supports
And and Or operators.
x And y x Or y This expression is asking the question ‘are x and y both true?’
This expression is asking the question ‘are x or y both true?’
x y x And y x y x Or y
true true true true true true true false false true false true false true false false true true false false false false false false
In Visual Basic it is good practice to use brackets when using And and Or like the example below. Brackets determine
in what order to compare.
((8 <= 3) Or (6 <= 7)) And (4 >= 4) will return True
((false) Or (true)) And (true)
(true) And (true)
(true)
When you want your program to have
different outcomes you use selection
which is based on a condition.
GCSE Computer Science – VB Guide
13
b. If … Else Create a program where you are given the price of a drink dependent on the outside temperature.
Flowchart Pseudo code
VB code
1 Module Module1 2 'initialising variables 3 Dim strTitle As String = "Drinks Stand" 4 Dim strQuestion As String = "What is the temperature? " 5 Dim dblTemperature As Double = 0 6 Dim intPrice As Integer = 0 7 8 Sub Main() 9 Console.Title = strTitle 'setting console window title 10 11 'input temp from user 12 Console.WriteLine(strQuestion) 13 dblTemperature = Console.ReadLine() 14 15 'sets price dependent on temperature 16 If (dblTemperature > 20) Then 17 intPrice = 50 18 Else 19 intPrice = 25 20 End If 21 22 'output price of drink 23 Console.WriteLine("The price is " & intPrice & "p.") 24 25 Console.ReadLine() 26 27 End Sub 28 29 End Module
Save it as 6.a drinksStand_v1.vb and test that it works.
Notice that the If statement is not a single statement, but rather a group of
statements that when implemented form decision logic.
The If statement checks a particular logical expression. It executes some different
groups of statements, depending on whether that expression is true or false.
OUTPUT ”What is the temperature?”
INPUT dblTemperature
IF dblTemperature > 20 THEN
intPrice = 50
ELSE
intPrice = 25
END IF
OUTPUT “The price is “ & intPrice & “p.”
If (expression) Then ‘Code if true’ Else ‘Code if true’ End If
GCSE Computer Science – VB Guide
14
c. If… The Else keyword and the statement between Else and End If are optional.
The statement could be:
Try this example where a kid just opened a lemonade stand and you want the computer decide how much she
should charge for each cup.
We can do this and get the same result without the Else statement. Notice how this code is equivalent.
VB code
1 Module Module1 2 'initialising variables 3 Dim strTitle As String = "Drinks Stand" 4 Dim strQuestion As String = "What is the temperature? " 5 Dim dblTemperature As Double = 0 6 Dim intPrice As Integer = 25 7 8 Sub Main() 9 Console.Title = strTitle 'setting console window title 10 11 'input temp from user 12 Console.WriteLine(strQuestion) 13 dblTemperature = Console.ReadLine() 14 15 'sets price if user gives temperature over 20 16 If (dblTemperature > 20) Then 'changes price only if condition is true 17 intPrice = 50 18 End If 19 20 'output price 21 Console.WriteLine("The price is " & intPrice & "p.") 22 23 Console.ReadLine() 24 25 End Sub 26 27 End Module
Save it as 6.b drinksStand_v1.vb and test that it works.
d. If…ElseIf … Else Sometimes there are more than two options. I could walk OR cycle
OR get the bus OR get a lift. As well as If and Else, we can stick and
ElseIf in the middle.
The If/Endif structure can be modified to include and Else IF
statement to consider multiple logical expressions. Such a structure
is shown to the right.
Try this third drinks stand example and you want the computer
decide how much to charge for each cup with extra complexity.
The price is
initialised to 25
Change price only
if temperature is
greater than 20
If (expression) Then ‘Code if true’ End If
If (expression1) Then ‘code if true’ ElseIf (expression2) Then ‘code if true’ ElseIf (expression3) Then ‘code if true’ Else
‘code if expression1, expression2 and expression3 are all false’
End If
GCSE Computer Science – VB Guide
15
VB code
1 Module Module1 2 'initialising variables 3 Dim strTitle As String = "Drinks Stand" 4 Dim strQuestion As String = "What is the temperature? " 5 Dim dblTemperature As Double = 0 6 Dim intPrice As Integer = 0 7 8 Sub Main() 9 Console.Title = strTitle 'setting console window title 10 11 'input temp from user 12 Console.WriteLine(strQuestion) 13 dblTemperature = Console.ReadLine() 14 15 'sets price dependent on temperature 16 If (dblTemperature >= 25) Then 17 intPrice = 75 18 ElseIf dblTemperature >= 20 Then 19 intPrice = 50 20 Else 21 intPrice = 25 22 End If 23 24 'output price 25 Console.WriteLine("The price is " & intPrice & "p.") 26 27 Console.ReadLine() 28 29 End Sub 30 End Module
Save it as 6.c drinksStand_v1.vb and test that it works.
e. Calculation Machine - Extension Develop an extension to the Calculation Machine program
that you did in chapter 2 (page 6).
In the program the user should have a choice to either add,
subtract, multiply or divide two numbers. Ensure that the
result of the calculation is rounded to one decimal place.
Save it as 5.d CalculationMachine_v1.vb and test that it
works.
f. Grade Calculator Develop a program where you are given the grade for a test mark.
The input should be the test mark in percentage and the output should be the actual
grade.
Use an If..ElseIf..Else statement to solve this task.
Save it as 5.e GradeCalculator_v1.vb and test that it works.
Mark Grade
95 9
90 8
80 7
70 6
60 5
50 4
40 3
25 2
15 1
GCSE Computer Science – VB Guide
16
g. Nested Selection You can also write one or more if statements nested inside another selection statement. The following example used
a nested if statement.
Write a program where you input a username and check if it is equal to 16fred.bloggs. If it is, input a user
password, and check if the password is equal to adjLsfj135, otherwise output a message “Invalid username”. If
the password is correct, output “Access granted”, otherwise output a message “Invalid password”.
Flowchart Pseudo code
VB code
1 Module Module1
2 Dim strUsername As String 3 Dim strPassword As String 4 5 Sub Main() 6 7 Console.Write("Enter username: ") 8 strUsername = Console.ReadLine() 9 10 If strUsername = "16fred.bloggs" Then 11 12 Console.Write("Enter password: ") 13 strPassword = Console.ReadLine() 14 15 If strPassword = "adjLsfj135" Then 16 Console.WriteLine("Access granted ") 17 Else 18 Console.WriteLine("Invalid password") 19 End If 20 21 Else 22 Console.WriteLine("Invalid username") 23 End If 24 25 Console.ReadLine() 26 End Sub 27 End Module
Save it as 5.f Login_v1.vb and test that it works.
OUTPUT ”Enter username: “
INPUT strUserName
IF strUserName = “16fred.bloggs” THEN
OUTPUT ”Enter password: “
INPUT strPassword
IF strPassword = “adjLsfj135” THEN
OUTPUT “Access granted”
ELSE
OUTPUT “Invalid password.”
END IF
ELSE
OUTPUT “Invalid username”
END IF
GCSE Computer Science – VB Guide
17
h. Case Statement The case statement is designed for coding multiple choices in a program,
such as a menu of several options where the user will enter a choice.
You now going to look at how a case statement can be used instead of
an If statement. Let’s look at task
5.e CalculationMachine where we used an If..ElseIf statement
and see how we can use a Case statement instead.
VB code 2 Dim dblFirstNumber As Double 3 Dim dblSecondNumber As Double 4 Dim dblAnswer As Double 5 Dim intMenuChoice As Integer 6 Dim strTitle As String = "Calculation Machine" 7 8 Sub Main() 9 10 Console.Title = strTitle 11 12 Console.WriteLine("---Calculation Menu---") 13 Console.WriteLine("1. Addition") 14 Console.WriteLine("2. Subtraction") 15 Console.WriteLine("3. Multiplication") 16 Console.WriteLine("4. Division") 17 Console.Write("Select an option 1-4: ") 18 19 intMenuChoice = Console.ReadLine() 20 21 Console.WriteLine("") 22 23 Console.Write("Enter the first number: ") 24 dblFirstNumber = Console.ReadLine() 25 Console.Write("Enter the second number: ") 26 dblSecondNumber = Console.ReadLine() 27 28 If intMenuChoice = 1 Then 29 dblAnswer = dblFirstNumber + dblSecondNumber 30 ElseIf intMenuChoice = 2 Then 31 dblAnswer = dblFirstNumber - dblSecondNumber 32 ElseIf intMenuChoice = 3 Then 33 dblAnswer = dblFirstNumber * dblSecondNumber 34 ElseIf intMenuChoice = 4 Then 35 dblAnswer = Math.Round((dblFirstNumber / dblSecondNumber), 1) 36 End If 37 38 Console.WriteLine("") 39 Console.WriteLine("The answer is: " & dblAnswer) 40 41 Console.ReadLine()
Save it as 5.g GradeCalculator_v1.vb and test that it works.
Select Case input Case “A”
‘code if true’ Case “B”
‘code if true’ Case “C”
‘code if true’ Case Else
‘code if false’ End Select
GCSE Computer Science – VB Guide
18
i. Food Selection Using the Case statement write a menu system that asks the user to pick from a list of foods.
If the user picks a healthy option display a positive message, otherwise display a negative message.
Extension Modify this so that you ask someone who picks a healthy option of they want mayo, if they pick mayo display “ohh, you were so close to being healthy” or something similar.
Save it as 6.h Food Selection_v2.vb and test that it works.
GCSE Computer Science – VB Guide
19
6. Count controlled loop… - For…Next Iteration is a posh way of saying loop and means do something again.
Loops are absolutely vital in programming in order to avoid having to
write sequences of code out again and again. And they come in
different forms.
A for loop is used when we know how many times the loop will
iterate. This is called a count controlled loop – controlled by a
counter.
For i = Start To End
‘code to repeat’
Next
When we want to increment in something different to one we can set the steps we want it to increment in e.g. count in 5s.
For i = Start To End Step Increment
‘code to repeat’
Next
a. Counting Try this code:
VB code 1 Module Module1 2 3 Sub Main() 4 5 'loops 10 times 6 For i = 1 To 10 7 Console.WriteLine(i) 'output the value of i 8 Next 9 10 Console.ReadLine() 'line to stop console closing 11 12 End Sub 13 14 End Module
Save it as 5.a Counting_v1.vb and test that it works.
Edit loop You can be more specific with your loops by setting a start and an end number. Make a program that starts with 5:
VB code 5 'loops 10 times 6 For i = 5 To 10 7 Console.WriteLine(i) 'output the value of i 8 Next
Save it as 5.a Counting_v2.vb and test that it works.
When you want your program
to repeat sections of your code
you use iteration.
GCSE Computer Science – VB Guide
20
b. Potato count Create a program that displays the nursery rhyme ‘one potato, two potato’.
VB code 5 'loops 3 times 6 For i = 1 To 3 7 Console.WriteLine(i & " potato") 'outputs the value of i and potato 8 Next 9 10 Console.WriteLine(4) 'outputs 4 11 12 'starts at 5 and loops 3 times 13 For i = 5 To 7 14 Console.WriteLine(i & " potato") 'outputs the value of i and potato 15 Next 16 17 Console.WriteLine("more") 'outputs more
Save it as 6.b Potatoes_v2.vb and test that it works.
c. Count in 2s If we want a variable to be incremented by 2 instead of 1. To print out the even numbers between 2 and 10 we use a
loop with the keyword Step.
VB code 5 Console.Title = "Count in 2s" 'setting console title 6 7 'starts at 2 and loops 5 times 8 For i = 2 To 10 Step 2 9 Console.WriteLine(i) 'outputs the value of i 10 Next
Save it as 6.c EvenNumbers_v1.vb and test that it works.
d. Countdown To count down we use a negative number (-1). Instead of incrementing (+) we now decrement (-) by 1.
VB code 5 Console.Title = "Countdown" 'setting console title 6 7 'decrements from 10 to 1 8 For i = 10 To 1 Step -1 9 Console.WriteLine(i) 'outputs the value of i 10 Next
Save it as 6.d Countdown_v1.vb and test that it works.
e. Timetable challenge Try writing a program that will prompt for
an integer and print the correct times table
(from 0 to 12). Test with all of the tables
up to 12.
Save it as 6.e Timestables_v1.vb and
test that it works.
GCSE Computer Science – VB Guide
21
7. Condition controlled loops… - Do While…Loop Another way of looping is with the While loop. This loop is controlled by a specific condition. Iterations are repeated
continuously based on a certain criteria and allows repetition when the number of repetitions are unknown:
Do While (expression) ‘code to repeat while expression is true’ Loop
All the code between Do While and Loop is repeated while the given logical Expression is true. A while loop will not
execute even once if expression is false the first time through.
a. Counting version 2 Try this code:
VB code 1 Module Module1 2 'initialising variables 3 Dim intCounter As Integer = 1 4 5 Sub Main() 6 Console.Title = "Counting" 'setting console title 7 8 ' counting to 10 using condition controlled loop 9 Do While intCounter <= 10 10 11 Console.WriteLine(intCounter) 12 intCounter = intCounter + 1 'incrementing counter 13 14 Loop 15 16 Console.ReadLine() 17 18 End Sub 19 End Module
Save it as 7aCounting_v1.vb and test that it works.
b. Countdown version 2 Try this code:
VB code 2 'initialising variables 3 Dim intCounter As Integer = 10 4 5 Sub Main() 6 Console.Title = "Counting down" 'setting console title 7 8 ' counting down from 0 to 10 using condition controlled loop 9 Do While intCounter >= 0 10 11 Console.WriteLine(intCounter) 12 intCounter = intCounter - 1 'decrementing counter 13 14 Loop 15 16 Console.WriteLine("Blast off!")
Save it as 7bCounting_v1.vb and test that it works.
GCSE Computer Science – VB Guide
22
c. Squared values Find all the square numbers below 100:
VB code 2 'initialising variables 3 Dim intCounter As Integer = 1 4 Dim intResult As Integer = 1 5 6 Sub Main() 7 Console.Title = "Squared values" 'setting console title 8 9 ' looping until intResult is less than 100 10 Do While intResult < 100 11 12 intResult = intCounter ^ 2 13 Console.WriteLine(intCounter & " squared = " & intResult) 14 15 intCounter = intCounter + 1 'incrementing counter 16 17 Loop
Save it as 7cSquaredValues_v1.vb and test that it works.
d. Bike depreciation – Using Boolean flag A motorbike costs £2000 and loses 10% of its value each year. Print the bike’s value each
year until it falls below £1000.
In this task we will use a Boolean flag that we initialise to False. A ‘flag’ is just another
term for true/false condition. An If statement is then used to change the flag to True.
VB code 2 'initialising variables 3 Dim booStop As Boolean = False 4 Dim floBikeValue As Double = 2000 5 Dim intYear As Integer = 1 6 7 Sub Main() 8 Console.Title = "Motorbile depriciation" 'setting console title 9 10 ' usinga 11 Do While (booStop = False) 12 13 Console.WriteLine("Year " & intYear & " = £" & floBikeValue) 14 floBikeValue = floBikeValue * 0.9 'calculate bike value 15 intYear = intYear + 1 'incrementing year 16 17 If floBikeValue < 1000 Then 'test that bike value is less than 1000 18 booStop = True 'change booStop to true 19 End If 20 21 Loop
Save it as 7dBikeDepriciation_v1.vb and test that it works.
GCSE Computer Science – VB Guide
23
e. Guess the number In this task you will developed a computer version of Guess the Number where the computer picks a number
between 1 and 10 and you try to guess the number. Based on your guess, the computer then tells you if you are
correct, too low or too high. At the end of the game the user should be told how many turns it took to guess it right.
To generate a random number you need to use the Rnd function. Before using Rnd the Randomize statement needs
to be used.
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim intRandomNumber As Integer = Math.Round((6 * Rnd()) + 1)
Your task is to give the user repeated guesses until the computer’s number is guessed correctly.
Extension To extend the game give some more detailed clues and ask if they want to play again. Tell the user if they are cold,
warm or hot.
8. Condition controlled loops… - Repeat…Until A Repeat…Until loop is very similar to WHILE loop as iteration will continue based on the loop conditions. It is
therefore also able to work in situation where the number of iterations is unknown.
Do ‘code to repeat while expression is true’ Loop Until (expression)
Unlike a while loop the test is completed at the end of the iteration so the iterated code will always run at least once.
a. Counting version 3 VB code 2 Dim intCounter As Integer = 1 3 4 Sub Main() 5 6 Do 7 'output the counter value 8 Console.WriteLine(intCounter) 9 intCounter = intCounter + 1 'increment the counter 10 Loop Until intCounter > 10 11 12 Console.ReadKey() 13 End Sub
Save it as 8aCounter_v3.vb and test that it works.
GCSE Computer Science – VB Guide
24
b. Timetable quiz Write a program to test someone on a timetable. The user should be asked for a timetable and then random
questions should be asked based on that times table. After each guess the user should be asked if they want to
continue the program.
VB code 1 Module Module1 2 'initialising variables 3 Dim intTimeTable As Integer 4 Dim intFactor As Integer 5 Dim intCorrectAnswer As Integer 6 Dim intUserAnswer As Integer 7 Dim strAnotherGo As String 8 9 Sub Main() 10 Console.Write("Enter a timetable: ") 11 intTimeTable = Console.ReadLine() 12 Console.Write("") 13 14 Do 15 'generating a random value and calculates the total 16 Randomize() 17 intFactor = Math.Round((12 * Rnd()) + 1) 18 intCorrectAnswer = intTimeTable * intFactor 19 20 'outputs the question 21 Console.Write(intTimeTable & " * " & intFactor & " = ") 22 intUserAnswer = Console.ReadLine() 23 24 'checks if user was correct or not 25 If intCorrectAnswer = intUserAnswer Then 26 Console.WriteLine("Correct, well done!") 27 Else 28 Console.WriteLine("No, it is " & intCorrectAnswer) 29 End If 30 31 'asks user if they want another question 32 Console.Write("Do you want another go (Y/N): ") 33 strAnotherGo = Console.ReadLine() 34 35 Loop Until strAnotherGo = "N" 'stops loop if N is entered 36 37 Console.ReadKey() 38 39 End Sub 40 41 End Module
Save it as 8bTimetableQuiz_v1.vb and test that it works.
GCSE Computer Science – VB Guide
25
9. Arrays An array is a data structure that can hold a set of data items under a single identifier – an indexed list of data.
In the same way that a variable holds data of a specific data type and has a name that can be used to identify it, and
array also holds data of a specific type and can be referred to by its name or label. The major difference is that while
a variable can hold one data value, an array can hold multiple values.
To define an array you have to use the Dim keyword using the following syntax:
Dim strArrayStudents(4) As String
This defines an array that can hold 5 values of a string data type as an array begins with an index number of 0. Note
the naming convention for arrays where we still use the data type prefix but also adding ‘Array’ as a prefix together
with a name of what is stored e.g. strArrayStudents, intArrayMarks
a. Creating Array Build the program below, it populates the array automatically.
The first For loop stores values in the array and the second reads it from the array.
Line by line analysis Line 4 The array is defined by giving it a name (strArrayStudents) and stating the final index value (4).
The first index position of zero is assumed. The range of the array is (0:4), representing five
individually numbered items
Line 8 Outputs the individual items defined by their index position.
Save the file as 9aStudentArray_v1.vb and to run it.
Now read the data from the array and output it on the screen.
VB code 13 Console.Write("Hello ") 14 For i = 0 To 4 15 Console.Write(strArrayStudents (i) & ", ") 16 Next
Save it as 9aCreateArray_v2.vb and test that it works.
b. Stored Sports Array Build a programs that has an array of sports. The array is indexed using brackets ( ).
VB code 3 Dim strArraySports() As String = {"Football", "Rugby", "Hockey", "Tennis", "Swimming”,
“Badminton”} 4 5 Sub Main() 6 For i = 0 To 4 7 Console.WriteLine(strArraySports 8(i)) 8 Next 9 10 Console.ReadKey() 11 12 End Sub
VB code 2 Dim strArrayStudents(4) As String 8 For i = 0 To 4 9 Console.Write("User " & I +1 & ", enter name: ") 10 strArrayStudents(i) = Console.ReadLine() 11 Next
strArrayStudents (0) = "Pia" strArrayStudents (1) = "Amy" strArrayStudents (2) = "Tom" strArrayStudents (3) = "Zoe" strArrayStudents (4) = "Bob"
Nam
e o
f array
Ind
ex p
ositio
n
Valu
e sto
red
GCSE Computer Science – VB Guide
26
Save is as 9bSportsArray_v1.vb and test that it works.
c. Investigate and Manipulate a Sports Array Now extend this program. We now want to find out certain things and edit parts of this array. The program will use
the menu below. Make sure the program is commented and use meaningful variable names. Where suitable use the
methods that that Array object provides.
In this program you will also use the Array class. This provides methods for creating manipulating searching and
sorting arrays. There are also properties in the Array class which allows you to retrieve the length of the array.
Hints:
1. Use a for loop to print out a student in the list For i = 0 To strArraySports.Length – 1
2. Use the array name with its index value: strArraySports(0)
3. Use the array property to find length: strArraySports.Length
4. Use an array property to find last: strArraySports.Last
5. Use and assignment statement: strArraySports(1) = strSport
6. Use a loop counter and a condition controlled loop to find its position
7. Use the sort method Array.Sort(strArraySports)
8. Use the reverse method once you’ve sorted it Array.Reverse(strArraySports)
9. Use the ReDim Preserve to change the length of the list: ReDim Preserve strArraySports(intArrayLenth)
Save this as 9cSportsArray_v2.vb