Fundamentals of Programming: Functions and Procedures

From Wikibooks, open books for an open world
Jump to: navigation, search

UNIT 1 - ⇑ Fundamentals of Programming ⇑

← One-Dimensional Arrays Functions and Procedures Global and Local Variables →


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)

Declarations[edit]

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

4


'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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

16


Exercise: Functions and Procedures

What is the difference between a function and procedure?

Answer :

Functions return values, Procedures don't

Why would you use subroutines (functions and procedures) in your code?

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 average:

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

num1 = 4
num2 = 7
num3 = 10
Average = 7

Answer :

dim a, b, c as integer
console.write("input num1 = ")
a = console.readline()
console.write("input num2 = ")
b = console.readline()
console.write("input num3 = ")
c = console.readline()
console.write("Average = " & Avg(a,b,c))
Sub nameTimes(name, num)
  for x = 1 to num
    console.writeline(name)
  next
End Sub

For the procedure above list:

  • the identifier
  • the parameters, what are their data types?
  • create a procedure call to print out the name "Kane" 5 times.

Answer :

  • identifier = nameTimes
  • parameters = name (string) and num (integer)
  • nameTimes("Kane",5)

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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:

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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?

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

7

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

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

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

What is the output of the above code?

Answer :

  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

hello - goodbye
hello - hello

What is the difference between a parameter passed by Value and a parameter passed by Reference?

Answer :

A parameter passed by value copies the value of the parameter passed into the sub routine. Any changes made to this value do not impact on the original value.

A parameter passed by Reference passes a link to a variable. Any changes made to the parameter in the sub routine change the original variable.