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

Fundamentals of Programming

This document provides an introduction to built-in functions in programming languages. It discusses arithmetic functions like round and truncation that are used to manipulate numbers. It also covers string handling functions for working with text, including functions for length, position, substring extraction, concatenation, and conversion. Examples are given to illustrate how each function works.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
190 views

Fundamentals of Programming

This document provides an introduction to built-in functions in programming languages. It discusses arithmetic functions like round and truncation that are used to manipulate numbers. It also covers string handling functions for working with text, including functions for length, position, substring extraction, concatenation, and conversion. Examples are given to illustrate how each function works.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 34

Fundamentals of Programming: A program

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.

console.writeline("6 * 6 = " & 6 * 6)

9.
10.

console.readline()

11.
12.

end sub

13. end module


14.
We'll take a look at each line:
1. module module1 - this line tells the computer that this particular program is called module1
2. sub main defines the section of code that is executed first
3. console.writeline("Hello...29") - this line writes plain text to the console window.
There are lots of other console commands we can perform such
as console.beepand console.color. We'll learn about them in the input/output section
4. console.writeline("6 * 6 = " & 6 * 6) - this writes out a combination of text
(everything between the "speech marks") and calculation (6*6), joining the two together with
the ampersand (&).
5. console.readline() - If you are running VB from a command line this won't be necessary,
but for people using Visual Studio it is. console.readline() waits for you to hit the return
key. Modern computers are very fast and if you didn't have this then the words displayed on
the screen would appear and then disappear too fast for the eye to see, the screen would
appear, then instantly disappear, take this line out and see what I mean.
6. end sub defines the end of the main code section.
7. end module - signifies the end of the small program we have written
This should output the following:
Code Output

Hello there, my name is Peter and my age is 29


6 * 6 = 36

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:

Exercise: Hello World!

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.

console.writeline("My name is Dave and this homework is too easy.")

9.
10.

console.writeline("2 + 2 = " & 2 + 2) 'bonus points for using a sum!

11.
12.

console.writeline("")

13.
14.

console.writeline("Yours Sincerely,")

15.
16.

console.writeline("Dave")

17.
18.

console.readline()

19.
20.

end sub

21. end module

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.

Dim name As String

3.
4.

Dim age As Integer

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.

Console.WriteLine("Bye " & name & "!")

15.
16.

Console.ReadLine()

you might be expecting it to print out:


Hello name you are age years old
But instead it says:
Code Output

Hello Peter you are 29 years old


This also means you are 348 months old
Bye Peter!
What a friendly program! Let's break it down line by line:
1. dim is a variable declaration, creating a temporary data store, a variable, and calling

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

better use speech marks - "Peter"

4. The variable age that we created earlier is now assigned a value and as it's an integer we

better not use speech marks - 29


5. This line writes things to the screen, starting with the text "Hello " which attaches that

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

The value stored in identifierName is: 7

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.

What will the following code output:


1. dim x, y as integer
2.

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 String handling functions


o

2.1 Length

2.2 Position

2.3 Substring

2.4 Concatenation

2.5 String conversion functions

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.

Extension: Random numbers

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)

Console.WriteLine("Please guess the random number between 1 and 100")


Do

Exercise: Arithmetic function


What does the following code output:
dim num1 as single = 12.75
dim num2 as single = 12.499
dim total as single
num2 = Math.Round(num2, 1)
num1 = Math.Truncate(num1)
total = num1 + num2
console.writeline(Math.Round(total))
[Collapse]
Answer :
Code Output

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

Please insert a decimal number: 13.78


The whole number part of this number is: 13
The decimal part is: 0.78
[Collapse]
Answer :
dim num as single
console.write("Please insert a decimal number: ")
num = console.readline()
console.writeline("The whole number part of this number is: " & Math.Truncate(num))

console.writeline("The decimal part is: " & num - Math.Truncate(num))

String handling functions[edit]


Very popular examination questions involve manipulating strings. These simple functions will help
you with this task.
Length[edit]
This function is used to find the length of any string you pass it, counting all the characters, including
the spaces. In visual basic to find the length of a string we use the Len("some string") function
that returns the integer length of the string that it has been passed:
someText = "Gary had a little lamb"
Console.writeline(Len(someText))
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

Hello Charles. How are you today?

String conversion functions[edit]


When you declare a variable you give it a datatype. This datatype restricts the values that you can
place into the variable. For example:

dim age as integer

would allow: age = 34


would NOT allow: age = "cabbages"
This seems to make sense, but what would happen when you try to place a real number
into a integer:
dim age as integer
age = 34.3
console.writeline(age)
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

Exercise: String functions

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 :

Dim name As String


console.write("Input: ")
name = console.readline()
console.writeline("Hello " & name & " you have " & Len(name) & " letters in you

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

Input: Elizabeth Sheerin


Firstname: Elizabeth
Surname: Sheerin
[Collapse]
Answer :
Dim name As String = "Elizabeth Sheerin"
Dim firstname, secondname As String
Dim space, textlength As Integer
space = InStr(name, " ")
textlength = Len(name)
firstname = name.Substring(0, space)
secondname = name.Substring(space, textlength - space)
Console.WriteLine("first name is: " & firstname)
Console.WriteLine("second name is: " & secondname)

A telephone number has been typed into a computer as a string: (01234)567890

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

Name of best friend: Beanie(CORRECT)


Name of best friend: jonny5(STOP THIS)

To do this we can match the input string against some rules, regular expressions or regex, in this case we
[A-Z][a-z]+

Breaking apart the rule:

[A-Z] - start exactly one instance of a capital letter

[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

to/from integer, real, date/time.

Arrays

A diagram showing how a 2d array works, the equivalent of the following:


dim animals(3) as string
animals(0) = "Dog"
animals(2) = "Cat"

Dim friends(0 To 2) As String


friends(0) = "Barry"
friends(1) = "Aubrey"
friends(2) = "Gertrude"
You can also declare arrays by placing the values directly into them, this code does exactly the same
as the above:
Dim friends() As String = {"Barry", "Aubrey", "Gertrude"}
You can pick out individual items by using their index
Console.WriteLine(friends(2))
Console.WriteLine(friends(0))
Would output:
Code Output

Gertrude
Barry

You can treat indexed array items as variables and change their values:
friends(0) = console.readline()

Exercise: One-Dimensional Arrays


Declare an array listing 5 animals in a zoo (aardvark, bear, cuckoo, deer, elephant) in alphabetical order:
[Collapse]
Answer :
dim zooanimals() as string = {"aardvark","bear","cow","deer","elephant"}

Write code to output the first and last animal


[Collapse]
Answer :
console.writeline(zooanimals(0))
console.writeline(zooanimals(4))

Someone has accidentally eaten the cuckoo, let the user add a new third animal and print them all out:
Code Output

Insert new third animal: Crocodile


1: Aardvark
2: Bear
3: Crocodile
4: Deer
5: Elephant
[Collapse]
Answer :
console.write("Insert new third animal:")
zooanimals(2) = console.readline()
console.writeline("1: " & zooanimals(0))
console.writeline("2: " & zooanimals(1))
console.writeline("3: " & zooanimals(2))
console.writeline("4: " & zooanimals(3))
console.writeline("5: " & zooanimals(4))
''Alternatively an A-grade student might write:
for x = 0 to 4
console.writeline(x + 1 & ": " & zooanimals(x))
next

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

To overwrite something, you treat it like a variable:


friends(1)="Peter"
For x As Integer = 0 To 2
Console.WriteLine(friends(x))
Next
Would output:
Code Output

Barry
Peter
Gertrude

Exercise: One-Dimensional Arrays


What is the output of the following code:
dim primes() as integer = {2,3,5,7,11,13,17,19,23}
dim count = 8
While count >= 0
console.write(primes(count) & ", ")
count = count - 1
end while
[Collapse]
Answer :
Code Output

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

Insert best friends:


1: Nell
2: Al
3: Sean
4: Paley
5: Jon
You listed: Nell,Al,Sean,Paley,Jon
[Collapse]
Answer :
dim befr(5) as string
console.writeline("Insert best friends:")
for x = 1 to 5
console.write(x & ": ")

Extension: For each

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

fib(x+2) = fib(x) + fib(x+1)


next
console.writeline("The first 31 fibonacci numbers are:")
for y = 0 to 30
console.write(fib(y) & ",")
next

Exercise: Calculating with arrays


Update the above code to allow the user to input a number, then the program to store and display that many
[Collapse]
Answer :
dim size as integer
size = console.readline()
'integer is too small to hold this value so we change to single
dim fib(size) as single
'initiate the first two values
fib(0) = 0
fib(1) = 1
for x = 0 to size - 2
fib(x+2) = fib(x) + fib(x+1)
next
console.writeline("The first " & size & " fibonacci numbers are:")
for y = 0 to size
console.write(fib(y) & ",")
next

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

Who are you searching for:


Olamide
Olamide found at position : 2

Exercise: Searching arrays


Why do we have attendance.length - 1 in the above code?
[Collapse]
Answer :
As the array starts at location 0, the length of the array will be 1 more than the largest index number.

Adjust the code above to tell you when it hasn't found a person:
[Collapse]
Answer :

'there are multiple ways of doing this:


dim attendance() as string = {"Callum", "John", "Olamide", "Mathew", "Gabriel", "Don
dim search as string
dim found as boolean = false
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)
found = true
end if
next
if found = false then
console.writeline(search & " NOT found in the array")
end if

Functions and Procedures


To save you rewriting lots of code again and again you might use a sub routine, there are two types:
Procedures and Functions. For example in a program you wanted to know today's date, instead of
having to write a separate sub routine to calculate the date each time you wanted to work it out, you
would probably use date(). This is a function, when you call it, it returns a value. It was written by
someone else and you can keep reusing it as many times as you want. Any program written in

industry will use sub routines calling things like:console.writeline(), printScore(),


deleteRecord() . Procedures and Functions allow for you to:

Reuse code

structure your programming

Easily incorporate other peoples 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

Function printNumber() as Integer


return number1
End Function

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

Mounir is 17 years old

'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

Exercise: Functions and Procedures


What is the difference between a function and procedure?
[Collapse]
Answer :
Functions return values, Procedures don't

Why would you use subroutines (functions and procedures) in your code?
[Collapse]
Answer :

They help you structure your code

They allow you to create a common routine once and re-use as many times as you want

They allow you to share code with other programs

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

Exercise: ByRef and ByVal


Sub Main()
dim a as integer = 7
dim b as integer = 8
Add(a,b)
console.writeline(a)
End Sub
Sub Add(ByXXX num1 as integer, ByXXX num2 as integer)
num1 = num1 + num2
End Sub
What is the output of the above code when ByXXX = ByVal?
[Collapse]
Answer :
Code Output

What is the output of the above code when ByXXX = ByRef?


[Collapse]
Answer :
Code Output

15

Sub Swap(ByRef p as string, ByVal q as string)


dim temp as string
temp = p
p = q
q = temp
console.writeline(p & " - " & q)
End Sub
Sub Main()
dim s1 as string = "hello"
dim s2 as string = "goodbye"
Swap(s2, s1)
console.writeline(s2 & " - " & s1)
End Sub

You might also like