Fundamentals of Programming
Fundamentals of Programming
When you first load Visual Studio and select to run a Console Application, you will be presented
with some source code:
module module1
sub main()
end sub
end module
These lines of code will tell the computer what to do, currently they do very little and we need to get
started:
Tradition has it that the first program a programmer should write is "Hello World!". Write the
following sourcecode into a command line VB.NET programming environment:
module module1
sub main()
console.writeline("Hello World!")
end module
console.readline()
end sub
If you are using Visual Studio then you can make the program run by pressing F5 or hitting
the Run button that looks a little like this:
You should get the following output:
Code Output
Hello World!
There it is, you're on your way to becoming a programmer! There is a lot more to learn and over the
course of the next few sections you'll get a crash course in programming.
First of all let's look at another program and find out what it's doing:
1. module module1
2.
3.
4.
5.
6.
sub main()
console.writeline("Hello there, my name is Peter and my age is
29")
7.
8.
9.
10.
console.readline()
11.
12.
end sub
But wait a second, this program isn't much use! Your name probably isn't Peter and you're even less
likely to be 29. Time for you to write some code yourself:
Create a short program to write the following to the screen, replacing the name Dave with your own name (unless it a
Code Output
Dear Teacher,
My name is Dave and this homework is too easy.
2+2 = 4
Yours Sincerely,
Dave
[Collapse]
Answer :
1. module module1
2.
3.
4.
sub main()
5.
6.
console.writeline("Dear Teacher,")
7.
8.
9.
10.
11.
12.
console.writeline("")
13.
14.
console.writeline("Yours Sincerely,")
15.
16.
console.writeline("Dave")
17.
18.
console.readline()
19.
20.
end sub
22.
You can show your friends and family. But wait! It's a rubbish program if you want to share it
amongst your friends! Each one of them will have to go and change the source code, then hit run.
Rubbish unless you live in a country where everyone has the same name, let's call that country
'Davia', I'm pretty sure you don't live there. We better look at making a program that is a little more
interactive, where people can change parts of the program without having to keep re-writing it. For
that we'll need something called a variable.
Variables
Let's take a look at this program:
1.
2.
3.
4.
5.
6.
name = "Peter"
7.
8.
age = 29
9.
Console.WriteLine("Hello " & name & " you are " & age & "
years old")
10.
11.
Console.WriteLine("This also means you are " & age * 12 & "
months old")
12.
13.
14.
15.
16.
Console.ReadLine()
it name It also makes sure that whatever goes into name will be a string by setting it to as
string
2. We declare another variable called age and make sure it is stored as an integer (a whole
number)
3. The variable name that we created earlier is now assigned a value and as it's a string we
4. The variable age that we created earlier is now assigned a value and as it's an integer we
variable we saw earlier to, but instead of putting the variable name, it puts the contents of
the variable ("Hello Peter"), then it attaches some more text ("Hello Peter you are ") and
adds another variable, age. Even though age is an integer we can stick it together with a
string ("Hello Peter you are 29"). Then finally it uses the ampersand once more to attach the
final piece of text ("Hello Peter you are 29 years old)
6. This line works in pretty much the same way, but it does a calculation, working out the age in
months. Computers are like giant calculators and you can perform all the sums you can
perform on your little pocket calc performed and far far more using them!
7. The great things about variables is that we can use them again and again, here we say "Bye
" and using an ampersand stick on the name of the person. This is great, by using a variable
we only need to write "Peter" once and save it as name. If someone else came along and
wanted to change the program they just need to change the value of name. Programming is
all about being as lazy as possible.
8. Good old console.readline() stops the screen disappearing too fast
Variables work like labelled boxes that allow you to store things inside them to retrieve later.
What you have just seen is a declaration of two variables, name and age. A variable is a known or
unknown value that has been given a symbolic name. This allows the name to be used
independently of the value. It is advisable that a meaningful name for readability and convenience.
This name is known as the identifier. To declare a variable in VB.NET we do the following:
Dim identifierName As datatype
Most programming languages have rules about identifiers: they generally have to use only
Alphanumeric characters (a..Z0..9) and some languages are case sensitive (name != Name).
variable - short term memory used to store temporary values in programming code
Once you have declared a variable you need to assign it a value. Assignment, in programming
terms, is the giving of a value to a variable, for example:
identifierName = 7
Here we are assigning the value 7 to the variable identifierName, so when we
use identifierName, we mean the value 7:
1. dim identifierName as integer
2.
3. identifierName = 7
4.
5. console.writeline("The value stored in identifierName is: " &
identifierName)
6.
Producing:
Code Output
Exercise: Variables
Update the code above to display the age in days, hours, minutes and seconds. No use of calculators! Use the code
[Collapse]
Answer :
1. dim name as string
2.
3. dim age as integer
4.
5. name = "Syeda"
6.
7. age = 31
8.
9. console.writeline("Hello " & name & " you are " & age & " years old")
10.
11. console.writeline("This also means you are " & age * 12 & " months old")
12.
13. console.writeline("This also means you are " & age * 365 & " days old")
14.
15. console.writeline("This also means you are " & age * 365 * 24 & " hours old")
16.
17. console.writeline("This also means you are " & age * 365 * 24 * 60 & " minutes old"
18.
19. console.writeline("This also means you are " & age * 365 * 24 * 60 * 60 & " seconds
20.
21. console.writeline("Bye " & name & "!")
22.
23. console.readline()
24.
Give a good reason why you made age a variable in the previous code
[Collapse]
Answer :
To keep track of a changing value that is used in many places but only needs to be updated in one.
Buit-in functions
You need to be familiar with several programming routines that come built into most common
programming languages. These routines are very useful and should save you a lot of effort in writing
code to perform common tasks. You might be asked to use them in the exam so learn them!
Contents
[hide]
1 Arithmetic functions
o
1.1 Round
1.2 Truncation
2.1 Length
2.2 Position
2.3 Substring
2.4 Concatenation
Arithmetic functions[edit]
You'll have to be familiar with several
Round[edit]
The round function is used to round numbers to a limited number of decimal places using
the Math.Round() function
Math.Round(1.94, 1) 'Returns 1.9
Math.Round(1.95, 1) 'Returns 1.9 !0.5 rounds down!
Math.Round(1.96, 1) 'Returns 2.0
Math.Round(1.9445, 2) 'Returns 1.94
Math.Round(1.9545, 3) 'Returns 1.954
Math.Round(6.765, 2) 'Returns 6.76
Math.Round(1.9445) 'Returns 2 - the equivalent of saying round to 0 dp
Truncation[edit]
The truncate function returns the integer part of a number, regardless of the decimal places.
Math.Truncate(19.45) 'Returns 19
Math.Truncate(19.9999) 'Returns 19
This is particularly useful when you are trying to perform DIV in modular arithmetic.
An essential part of most games is the ability to use random numbers. These might be used to randomly place gold co
some distance.
Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()
The above code will give you a random number between 1 and 2,147,483,647. You might well require a number that i
in this case 5 and 10 you can use the following:
randomNumber = rndGen.Next(5,10)
So how exactly can we use this? Take a look at the following game:
Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do
console.write("your guess:")
guess = console.readline()
if guess > randomNumber
console.writeline("Too High")
end if
if guess < randomNumber
console.writeline("Too Low")
end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")
Adjust the code above to tell the user how many guesses they took to find the random number. HINT: you'll need a va
[Collapse]
Answer :
Sub Main()
Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess As Integer
Dim count As Integer = 1
randomNumber = rndGen.Next(1, 100)
24
Write some code to output the integer part of a number input by the user
[Collapse]
Answer :
Math.Truncate(input)
Write code to output the integer and decimal parts of an input number:
Code Output
22
Position[edit]
This function allows us to find the position of an item within a given string and returns the position's
location. In visual basic this is performed by the following command: InStr([string],
[item]) For example we might want to find the location of an end of a sentence by looking for a
fullstop:
someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))
Code Output
23
We can also use this command to search for strings within strings. For example if we were to look for
to see if a sentence contained a certain name:
someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))
Code Output
25
If the search item is not contained in the string then it will return 0
someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))
Code Output
Substring[edit]
This function allows you to snip items out of a string and return a substring. Visual Basic uses the
following command: [string].Substring([startPosition],[lengthOfReturnString]). For
example we might want to find the local number from a landline phone number we have been given.
We'll have to ignore the area code:
phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)
Code Output
567890
Concatenation[edit]
This function allows you to stick strings together (concatenate) so that you can start to build strings
using variables. Visual Basic uses the following command: [stringA & stringB] For example we
might have a users name stored in a variable dim name as string and a greeting that we would
like to give them:
name = "Charles"
console.writeline("Hello " & name & ". How are you today?")
Code Output
34
This might seem OK, but in other lanuages we might run into trouble. To perform this we
would have to convert from one datatype to another:
dim age as decimal
age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)
Code Output
34.3 34
Write a short program to tell someone how many letters they have in their name (just in case they don't k
Code Output
Input: Fremlin
Hello Fremlin, you have 7 letters in your name.
[Collapse]
Answer :
Some people have stupidly typed their firstname and their surname into a database, write some code to d
dim fistname as string = "Elizabeth Sheerin"
Code Output
Extension: REGEX
You will often want to check the format of a string being input and if it is incorrect you will want it to be sub
best friend, meaning that they shouldn't be inputting any letters or spaces, and it should start with a capita
Code Output
To do this we can match the input string against some rules, regular expressions or regex, in this case we
[A-Z][a-z]+
[a-z]+ - followed by as many lower case letters as you like (that's what the + means)
Another example might be checking for the correct spelling of a famous composer:
"Handel", "Hndel", and "Haendel"
We can check this using the pattern H(|ae?)ndel. Let's take a look at what this means:
H - start with an H
(|ae?) - includes an or (the | symbol) an a followed by an optional e (e? means the e is optio
Most regular expression tools provide the following operations to construct expressions.
Boolean "or"
A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey".
Grouping
Parentheses are used to define the scope and precedence of the operators (among other uses). For
the set of "gray" and "grey".
Quantification
A quantifier after a token (such as a character) or group specifies how often that preceding element is
? The question mark indicates there is zero or one of the preceding element. For example, colou
* The asterisk indicates there is zero or more of the preceding element. For example, ab*c match
Arrays
Gertrude
Barry
You can treat indexed array items as variables and change their values:
friends(0) = console.readline()
Someone has accidentally eaten the cuckoo, let the user add a new third animal and print them all out:
Code Output
To print out the entire array it is best to use some form of iteration:
For x As Integer = 0 To 2
Console.WriteLine(friends(x))
Next
Would print out:
Code Output
Barry
Aubrey
Gertrude
Barry
Peter
Gertrude
23,19,17,13,11,7,5,3,2
Declare an array that will hold the names of your 5 best friends, call is befr
[Collapse]
Answer :
dim befr(5) as string 'befr(4) would also be accepted
Write a loop so that you can input each of your five best friends and it will output them in the order you input them. Fo
Code Output
Sometimes you might not know the length of an array that you area dealing with yet you will still want to cycle through
x = 0 to ?? code then how will you cycle through everything? Visual Basic and most languages offer a for each r
one. This makes for far more robust code where you don't have to keep changing the variables of loops each time you
Dim someNumbers() as integer = {1,2,3,4,5,6,7,23,77}
For Each n In someNumbers
Console.Write(n & ", ")
Next
The above code would output:
Code Output
1, 2, 3, 4, 5, 6, 7, 23, 77,
Uses[edit]
Arrays are very useful for solving all manner of problems, ranging from sorting lists to storing the
results to calculations.
Take the Fibonacci sequence of numbers where: the first two numbers in the Fibonacci sequence
are 0 and 1, and each subsequent number is the sum of the previous two.
A tiling with squares whose sides are successive Fibonacci numbers in length
For example:
This could take some time to calculate by hand but and we can use an array to calculate
and store this sequence:
dim fib(30) as integer
'initiate the first two values
fib(0) = 0
fib(1) = 1
for x = 0 to 28
Arrays are also very important when we are searching and sorting data. You will learn a lot
more about this in A2, but for the moment take a look at this linear search routine:
dim attendance() as string = {"Callum", "John", "Olamide", "Mathew",
"Gabriel", "Dong"}
dim search as string
console.writeline("Who are you searching for:")
search = console.readline()
for x = 0 to attendance.length - 1 'why do we need -1 here?
if attendance(x) = search then
console.writeline(search & " found at position : " & x)
end if
next
If we were to try and find Olamide we should see the following:
Code Output
Adjust the code above to tell you when it hasn't found a person:
[Collapse]
Answer :
Reuse code
An easy way to tell the difference between a Procedure and a Function is to look at the names:
Functions are fun: if you would call them, they would return a value'
Procedures aren't fun: if you call them they don't return any value. (these are known
as sub in Visual Basic)
Contents
[hide]
1 Declarations
2 Calls
3 Parameters
o
3.1 ByRef
3.2 ByVal
Declarations[edit]
In VB.NET you declare a procedure by using the Sub command, so where
you see Sub below, please read as Procedure
Declarations are where you state the name of your procedure/function and the code that you want to
execute. Even if you declare a procedure/function, it doesn't mean that the code will run, you need
a Call to actually get the code to execute.
Sub printNumber()
console.writeline(number1)
End Sub
Functions are slightly different, as they return values you must include a return function in their
declaration. And you must specify the datatype of the value being returned, in the case below that is
an Inteteger specified by: ..) as Integer
Calls[edit]
Calls allow you to run the code declared in a procedure/function. You can build up all sorts of
programming structures by making Calls part of the code. Remember that Functions are fun, so you
should be doing something with the returned value.
printNumber() ' a procedure call
console.writeline(printNumber()) ' a function call
dim x = MaximumSpeed() ' another function call
Parameters[edit]
Parameters allow you to pass values to the procedures and functions that you declare, you can pass
all sorts of datatypes as parameters and you can pass as many as you like
'declaration
Sub printNumber(number1 as integer) 'one parameter
console.writeline(number1)
End Sub
'...
'call
printNumber(4)
The output would be:
Code Output
'declaration
Sub printNameAge(name as string, age as integer) 'two parameters
console.writeline(name & " is " & age & " years old")
End Sub
'...
'call
printNameAge("Mounir", 17)
The output would be:
Code Output
'declaration
function squareNumber(number1 as integer) as integer 'one parameter
return (number1 * number1)
End Function
'...
'call
console.writeline(squareNumber(4))
Note that as it's a function, we had to include the call in an equation. It returns a value, it can't sit on
its own. The output would be:
Code Output
16
Why would you use subroutines (functions and procedures) in your code?
[Collapse]
Answer :
They allow you to create a common routine once and re-use as many times as you want
They allow you to test sub routines independently of the rest of the code
Write a function declaration with the identifier of Avg that will accept 3 numbers (num1, num2, num3) and return the a
[Collapse]
Answer :
Function Avg(num1, num2, num3)
return (num1 + num2 + num3) / 3
End Function
For the above function, write code with a function call to work out the average of three numbers input by a user:
Code Output
num1 = 4
num2 = 7
num3 = 10
Average = 7
[Collapse]
Answer :
dim a, b, c as integer
console.write("input num1 = ")
ByRef[edit]
The parameter that you are passing to a procedure or function is referred to. That means you are
pointing at it, you are going to directly change its value and anything that happens to it within the
procedure or function will change the original value.
Dim number1 as integer = 123
Sub Main()
console.writeline(number1)
IncPrintNumber(number1)
console.writeline(number1)
End Sub
Sub IncPrintNumber(ByRef num as integer)
num = num + 1
console.writeline(num)
End Sub
The output would be:
Code Output
123
124
124
ByVal[edit]
The parameter that you are passing to a procedure or function is copied. That means you are taking
a copy of the original value put into the procedure or function call. Anything that happens to it within
the procedure or function will NOT change the original value.
Dim number1 as integer = 123
Sub Main()
console.writeline(number1)
IncPrintNumber(number1)
console.writeline(number1)
End Sub
Sub IncPrintNumber(ByVal num as integer)
num = num + 1
console.writeline(num)
End Sub
This saves a local variable of the number1 value, storing it in num, it is only valid inside the
IncPrintNumber sub routine The output would be:
Code Output
123
124
123
15