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

Aqa 8525 NG Vbnet

Uploaded by

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

Aqa 8525 NG Vbnet

Uploaded by

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

Notes and guidance: VB.

NET
The VB.NET code is described below to help students prepare for their AQA GCSE Computer Science exam (8525/1).
We will use a consistent style of VB.NET code in all assessment material. This will ensure that, with enough preparation, students will understand
the syntax of the code used in assessments. Students do not have to use this style of code in their own work or written assessments, although they
are free to do so. The only direction to students when answering questions or describing algorithms written in code is that their code is clear, consistent
and unambiguous.
This resource may be updated as required and the latest version will always be available on our website. It is not confidential and can be freely shared
with students.

General Syntax
• Code is shown in this font
• DataType means a datatype such as Integer, Single, Double, Boolean, Char or String.
• Exp means any expression.
• IntExp, RealExp, BoolExp, StringExp, CharExp and ListExp mean any expression which can be evaluated to an integer, real,
Boolean (False or True), string, character or list respectively.

Indentation
VB.NET code will use indentation to indicate the range of statements controlled by iteration and selection statements (as well as declarations for
subroutines). Indentation will be shown with three spaces per indentation level, although if doing so makes lines too long for the page, this may be
reduced to two spaces. Questions will show indentation guides (vertical lines) within the answer space. Students should be encouraged to use
these to explicitly show their indentation.
Comments

Single line comments ' A comment

' A comment
Multi-line comments
' Another comment

String and character literals


String and character literals will be delimited using the " (double quote) character.

© 2023 AQA 2 of 22
Variables and constants
Variable names will be written in camel case eg numberOfItemsSold. Camel case is the practice of writing phrases without spaces or
punctuation, indicating the separation of words with a single capitalised letter and the first word starting with either case.
Constant names will be written in upper case, using an underscore to indicate a break between words, eg ACCELERATION_DUE_TO_GRAVITY.
Questions will use meaningful variable names wherever possible, eg quantityInStock, quantity or qty rather than just n to hold the
quantity of an item in stock. For layout and/or lack of context reasons, this resource may not always follow this advice. This rule may not be followed
for common idioms, eg using i as a loop index or for exam-related reasons.
Before a variable is used, it will be declared in a Dim statement. This will give the name of the variable, its data type and, optionally, an initial value.
Note that multiple variables may be defined in the same Dim statement and given the same data type. If an initial value is given and its data type is
unambiguous then the data type may be omitted; "S", 0 are examples of ambiguous values since "S" could be a string or a character, and 0 could
be integer or single.

Dim aNumber As Integer


Dim anotherNumber As Integer = 0
Dim Identifier As DataType
Variable declaration Dim theString, Message As String
Dim Identifier As DataType = Value
' Both theString and Message are
' declared as strings
aNumber = 3
anotherNumber = aNumber + 1
Variable assignment Identifier = Exp theString = "Hello"
message = "Invalid number"
totalNumberOfItems = 0
Const IDENTIFIER = Exp Const CLASS_SIZE = 23
Const PI = 3.141
Constant declaration
Const IDENTIFIER As DataType = Value Const TOTAL As Single = 0.0

© 2023 AQA 3 of 22
Arithmetic operations
Used in the normal way with brackets to indicate
precedence where needed. So, a + b * c would
multiply b and c together and then add the result to a,
+ whereas (a + b) * c would add a and b together
- and then multiply the result by c.
Standard arithmetic operations
*
/ Brackets may be used to indicate precedence even
where not strictly necessary, eg testing for divisibility
by 3 could be written as (n Mod 3) = 0 rather
than n Mod 3 = 0
9 \ 5 evaluates to 1
Integer division IntExp \ IntExp 5 \ 2 evaluates to 2
8 \ 4 evaluates to 2

9 Mod 5 evaluates to 4
Modulus operator IntExp Mod IntExp 5 Mod 2 evaluates to 1
8 Mod 4 evaluates to 0

© 2023 AQA 4 of 22
Relational operators for types that can be clearly ordered (numbers, strings, characters)
4 < 6
Less than Exp < Exp "A" < "B"
"adam" < "adele"

Greater than Exp > Exp 4.1 > 4.0

Equal to Exp = Exp 3 = 3

Not equal to Exp <> Exp qty <> 7

3 <= 4
Less than or equal to Exp <= Exp
4 <= 4
4 >= 3
Greater than or equal to Exp >= Exp
4.5 >= 4.5

Boolean operations

Logical AND BoolExp And BoolExp (3 = 3) And (3 <= 4)

Logical OR BoolExp Or BoolExp (x < 1) Or (x > 9)

Logical NOT Not BoolExp Not (a < b)

© 2023 AQA 5 of 22
Indefinite (condition controlled) iteration
Dim a As Integer = 1
While a < 4
Console.WriteLine(a)
a = a + 1
End While
' outputs 1, 2, 3
WHILE (while the Boolean expression is
True, repeat the statements). If the While BoolExp whereas
Boolean expression is False the first ' indented statements here
time the While statement is reached End While Dim a As Integer = 5
then the indented statements are never While a < 4
executed. Console.WriteLine(a)
a = a + 1
End While
' does not output anything since
' a < 4 is false the first time the
' While is encountered

© 2023 AQA 6 of 22
Indefinite (condition controlled) iteration (continued)
Dim a As Integer = 1
Do While a < 4
Console.WriteLine(a)
a = a + 1
Loop
' outputs 1, 2, 3

Another form of the WHILE works in Do While BoolExp whereas


exactly the same way as above (notice ' indented statements here
the similarity between this form and that Loop Dim a As Integer = 5
in REPEAT-UNTIL). Do While a < 4
Console.WriteLine(a)
a = a + 1
Loop
' does not output anything since
' a < 4 is false the first time the
' While is encountered
Dim a As Integer = 1
Dim carryOn As String
Do
Do Console.WriteLine(a)
REPEAT-UNTIL (repeat the statements
until the Boolean expression is True).
' indented statements here a = a + 1
Loop Until BoolExp Console.Write("Continue? ")
The indented statements are always
executed at least once. carryOn = Console.ReadLine()
Loop Until carryOn = "N"
' outputs 1, … until "N" is entered

© 2023 AQA 7 of 22
Definite (count controlled) iteration
For i As Integer = 0 To 6
Console.WriteLine(i)
For Identifier As DataType = IntExp1 To IntExp2 Next
' indented statements here ' outputs 0, 1, 2, 3, 4, 5, 6
Next
FOR
' Identifier will first have the value IntExp1,
(repeat the statements For i As Integer = 1 To 7
the number of times
' then IntExp1 + 1, IntExp1 + 2, all the way
Console.WriteLine(i)
indicated, each time giving the ' up (still in steps of 1) to the value of Next
loop variable (Identifier) ' IntExp2
' outputs 1, 2, 3, 4, 5, 6, 7
the value of the next
value/number in the range). For Identifier As DataType = IntExp1 To IntExp2 Step IntExp3
As DataType may be
' indented statements here For i As Integer = 1 To 7 Step 2
Next Console.WriteLine(i)
omitted if the type is ' Identifier will first have the value IntExp1,
unambiguous (see the fourth Next
' then IntExp1 + IntExp3, IntExp1 + 2 * IntExp3, ' outputs 1, 3, 5, 7
example).
' all the way up (or down if IntExp3 is negative)
' to the value of IntExp2 For i = 7 To 1 Step -2
Console.WriteLine(i)
Next
' outputs 7, 5, 3, 1

© 2023 AQA 8 of 22
Definite (count controlled) iteration (continued)
Dim length As Integer = 0
For Each ch In message
length = length + 1
Next
Console.WriteLine(length)
' calculate the number of
' characters in message
' and output it
FOR
(repeat the statements Dim reversed As String = ""
the number of times For Each Identifier In StringExp
For Each ch In message
that there are characters ' indented statements here
reversed = ch + reversed
in a string, each time giving Next
Identifier the value of the Next
next character in the string). Console.WriteLine(reversed)

' reversed is set to the


' reverse of message and
' output
' eg if message = "Hello"
' then reversed will become
' "olleH"

© 2023 AQA 9 of 22
Selection

IF-THEN-ENDIF (execute the If BoolExp Then Dim a As Integer = 1


statements only if the Boolean ' indented statements here If (a Mod 2) = 0 Then
expression is True: see VB.NET End If Console.WriteLine("even")
Boolean expressions above). End If
Dim a As Integer = 1
IF-THEN-ELSE-ENDIF (execute If BoolExp Then
If (a Mod 2) = 0 Then
the statements following the THEN ' indented statements here
Console.WriteLine("even")
if the Boolean expression is True, Else
Else
otherwise execute the statements ' indented statements here
Console.WriteLine("odd")
following the ELSE). End If
End If
a = 1
If (a Mod 4) = 0 Then
Console.WriteLine("multiple of 4")
If BoolExp Then
NESTED IF-THEN-ELSE ENDIF Else
' indented statements here
(use nested versions of the above If (a Mod 4) = 1 Then
Else
to create more complex Console.WriteLine("remainder 1")
If BoolExp Then
conditions). Else
' indented statements here
If (a Mod 4) = 2 Then
Else
Note that IF statements can be Console.WriteLine("remainder 2")
nested inside the THEN part, the
' indented statements here
Else
ELSE part or both. End If
Console.WriteLine("remainder 3")
End If
End If
End If
End If

© 2023 AQA 10 of 22
Selection (continued)

Dim a As Integer = 1
If BoolExp Then
If (a Mod 4) = 0 Then
' indented statements here
Console.WriteLine("multiple of 4")
ElseIf BoolExp Then
ElseIf (a Mod 4) = 1 Then
IF-THEN-ELSE IF ENDIF ' indented statements here
Console.WriteLine("remainder of 1")
(removes the need for multiple ' possibly more ElseIfs
ElseIf (a Mod 4) = 2 Then
indentation levels). Else
Console.WriteLine("remainder of 2")
' indented statements here
Else
End If
Console.WriteLine("remainder of 3")
End If

© 2023 AQA 11 of 22
Arrays
Dim Identifier(IntExp) As DataType Dim primes(5) As Integer
' IntExp is the highest value element ' Has 6 elements, primes(0) to primes(5)
' that can be accessed. Since the first
' element is element 0 there are
Dim evens() As Integer = {2, 4, 6, 8, 10}
' IntExp + 1 elements in the array
Declaration ' Has 5 elements, evens(0) to evens(4)
Dim Identifier() As DataType = {value, …}
' In this form there are the number of Dim names() = {"John", "Paul", "George"}
' elements in the array that there are in ' If the type of the elements is clear
' {value, …} ' then As DataType can be omitted
primes = {2, 3, 5, 7, 11, 13, 17, 19}
Assignment Identifier = {Exp, … ,Exp} ' Note that primes will now have 8 elements
' primes(0) to primes(7)

Console.WriteLine($"Only even prime is


Accessing an element {primes(0)}")
Identifier(IntExp)
(indexing)
' prints "Only even prime is 2"

primes(5) = 17

Updating an element Identifier(IntExp) = Exp ' position 5 within the array now
' contains the value 17

© 2023 AQA 12 of 22
Arrays (continued)
Dim board(7, 7) As String
' board has 64 elements each of which is
' a string. board(0, 0) to board(7, 7)

Dim game(,) As String = {{"O", " ", "X"},


{"X", "O", " "},
Declaring a two- Dim Indentifier(IntExp1, IntExp2) As DataType {"O", "X", "O"}}
dimensional array Dim Identifier(,) As DataType = {{value, …}, …} ' game has 9 elements, game(0, 0) to
' game(2, 2)

Dim prices(,) = {{2.56, 4.34},


{11.96, 12.41}}
' As DataType omitted

Dim game(,) As String = {{"O", " ", "X"},


{"X", "O", "?"},
{"O", "!", "X"}}
Console.WriteLine($"Row 1 column 2:
{game(1, 2)}")
Accessing an element in a
Identifier(IntExp, IntExp) ' prints "Row 2 Column 3: ?" as the
two-dimensional array
' third column (with index 1) of the
' second row (with index 2) in array is "?"

' Note that game(2, 1) would be "!" and


' that game(3, 1) would give an error
' since there is no fourth row

© 2023 AQA 13 of 22
Arrays (continued)
game(1, 2) = "#"

' game is now


Updating an element in a
Identifier(IntExp, IntExp) = Exp ' {{"O", " ", "X"},
two- dimensional array
' {"X", "O", "#"},
' {"O", "!", "X"}}

Dim evens() As Integer = {2, 4, 6, 8, 10}


evens.Length
' evaluates to 5 using example above

Dim board(7, 7) As String


board.Length
Array length Identifier.Length ' evaluates to 64 using example above

Dim costs(4, 3) As Single


costs.GetLength(0)
' evaluates to 5 and
costs.GetLength(1)
'evaluates to 4
Dim t(,) As Integer = {{1, 2}, {2, 4}, {3, 6}}

Console.WriteLine($"The entire array t contains {t.Length} items")


Console.WriteLine($"There are {t.GetLength(0)} sub arrays")
Further examples of array Console.WriteLine($"Each sub array contains {t.GetLength(1)} items")
lengths
' outputs:
' The entire array t contains 6 items
' There are 3 sub arrays
' Each sub array contains 2 items

© 2023 AQA 14 of 22
Arrays (continued)
Dim a() As Integer = {15, 27, 19, 18}
FOR Dim sum As Integer = 0
(repeat the statements For Each age In a
the number of times sum = sum + age
For Each Identifier In Array
that there are elements in a Next
' indented statements here
array, each time giving Dim mean As Single = sum / a.Length
Next
Identifier the value of the Console.WriteLine(mean)
next element in the array). ' calculates the total of the ages
' held in the array and the mean
' age and then outputs the mean (19.75)

© 2023 AQA 15 of 22
Records
Structure RecordName
Dim field1 As DataType Structure Car
Dim field2 As DataType Dim make As String
… Dim model As String
Sub New(param1 As DataType, Dim reg As String
param2 As DataType,
Record declaration (exam …) Sub New(mk As String,
questions will use this method to Me.field1 = param1 md As String,
declare and use records) Me.field2 = param2 rg As String)
… Me.make = mk
End Sub Me.model = md
End Structure Me.reg = rg
End Sub
' The name of the structure End Structure
' will start with a capital letter.
Dim myCar As New Car("Ford",
Dim varName As New
Variable instantiation "Focus",
StructureType(value, …)
"EF56 ZFG")
myCar.model = "Fiesta"
Assigning a value to a field in a
varName.field = Exp
record ' The model field of the myCar
' record is assigned the value "Fiesta".
Console.WriteLine(myCar.model)
Accessing values of fields within
varName.field
records ' Outputs the value stored in the
' model field of the myCar record

© 2023 AQA 16 of 22
Subroutines
Note: subroutines that are defined using the keyword Sub are procedures, while those that are defined using the keyword Function are functions and use
the Return statement to return a value.

Sub Identifier(parameter As Type, …) Sub showAdd(a As Integer, b As Integer)


' indented statements here Dim result As Integer = a + b
End Sub Console.WriteLine(result)
End Sub
Function Identifier(parameter As Type)
Subroutine definition
As ReturnValueType Sub sayHi()
' indented statements here Console.WriteLine("Hi")
' including at least one return End Sub
' statement
End Function ' Both of these subroutines are procedures
Function add(a As Single, b As Single) As
Single
Dim result As Single = a + b
Subroutine return value Return Exp Return result
End Function

' This subroutine is a function


' Subroutine without a return value
showAdd(2, 3)
' Subroutines without a return value
' Subroutine with a return value
Identifier(parameters)
Dim n1, n2 As Single
Calling subroutines
Console.Write("First number? ")
' Subroutines with a return value
n1 = Console.ReadLine()
Console.Write("Second number? ")
Identifier = Identifier(parameters)
n2 = Console.ReadLine()
Dim answer As Single = add(n1, n2) * 6

© 2023 AQA 17 of 22
String handling

"computer science".Length
String length StringExp.Length
' evaluates to 16 (includes space)
"computer science".IndexOf("m")
' evaluates to 2

Position of a character StringExp.IndexOf(CharExp) Dim t As String = "Algorithms"


Dim s As Integer = t.IndexOf(" ")
' s will have the value -1 since
' t does not contain a space
Dim t As String = "Computer Programs"
Dim p As String = t.Substring(9, 8)
Substring (the substring runs from ' prints the string "Programs"
the character at the first IntExp,
' If there is only one number then the
starting at 0, for the number of StringExp.Substring(IntExp, IntExp)
' string from the position given to
characters given by the second
' the end of the string is returned
IntExp).
Dim t As String = "Computers"
Console.WriteLine(t.Substring(3))
' prints "puters"
Accessing a single character in a Dim t As String = "Computers"
string (this treats a string as if it StringExp(IntExp) Console.WriteLine(t(2))
were an array) ' prints "m"
Console.WriteLine("C" + "S")
' prints the string "CS"
Concatenation StringExp + StringExp
' Note that no space is automatically
' added between each string

© 2023 AQA 18 of 22
String and character conversion

Convert.ToInt32("16")
Converting string to integer Convert.ToInt32(StringExp)
' evaluates to the integer 16

Convert.ToSingle("16.3")
Converting string to real Convert.ToSingle(StringExp)
' evaluates to the single (real) 16.3
Convert.ToString(16)
Converting integer to string Convert.ToString(IntExp)
' evaluates to the string "16"
Convert.ToString(16.3)
Converting real to string Convert.ToString(RealExp)
' evaluates to the string "16.3"
Asc("a")
Converting character to
Asc(CharExp)
character code
' evaluates to 97 using ASCII/Unicode
Chr(97)
Converting character code to
Chr(IntExp)
character
' evaluates to "a" using ASCII/Unicode

© 2023 AQA 19 of 22
Input/output
Dim name As String = Console.ReadLine()
' Console.ReadLine() returns a string,
' so one of the conversion functions
' above must be used to convert the
' string to an integer (Convert.ToInt32)
' or a single (Convert.ToSingle) unless
Console.ReadLine() ' assigning the result to a variable with
' one of those types.
' If you need a prompt then use Console.Write("What is your name? ")
User input ' Console.Write(prompt) before Dim name As String = Console.ReadLine()
' using Console.ReadLine
Console.Write("How many cans? ")
Dim q As Integer = Console.ReadLine()
' Note no Convert.ToInt32

Console.Write("How much? ")


Dim price As Single = Console.ReadLine()
' Note no Convert.ToSingle

© 2023 AQA 20 of 22
Input/output (continued)
Dim a As Integer = 45;
Console.Write(a);
Dim g As Single = 23.45;
Console.Write(g);

' To output more than one thing, or to


' include text at the same time
' use $ strings, eg
Console.WriteLine(Exp)
Dim qty As Integer = 15;
Output Console.WriteLine($"Quantity {qty}");
Console.Write(Exp)
' Doesn't move to new line after
' outputs the string "Quantity 15"
' outputting Exp
Console.WriteLine("Mary had ")
Console.WriteLine("a little lamb")
' will print the text over two lines, but

Console.Write("Mary had ")


Console.WriteLine("a little lamb")
' will print the text on the same line
Dim name = "BT"
Dim staff = 125000
Formatted outputs will be shown
using interpolated strings ($"" $"…{identifier}…{identifier}…" Console.WriteLine($"{name} has {staff}
strings). staff")

' outputs "BT has 125000 staff"

© 2023 AQA 21 of 22
Random number generation

Random integer generation Dim Identifier As New Random() Dim rGen As New Random()
(The first IntExp is inclusive, Dim num1 As Integer = rGen.Next(3, 7)
the second IntExp is Dim varName As Integer =
exclusive.) Identifier.Next(IntExp, IntExp) ' generates an integer between 3 and 6

© 2023 AQA and its licensors. All rights reserved. 22 of 22

You might also like