Visual Basic 2010 (Console) Guide
Functions
In the previous section we learned that we can group statements together in a reusable block of code called a procedure. The procedure can have parameters and can be called from our main program as many times as we like.
Functions differ from procedures in that they can return a value. This means that they can be used as the right hand side of a statement. Functions must include the data type of the returned value in their declaration. Copy and compile the following example.
Sub Main()
Dim strEnteredText As String
strEnteredText = GetInput()
Console.WriteLine("You wrote {0}", strEnteredText)
Console.ReadLine()
End Sub
Function GetInput() As String
Dim strTemp As String
Console.Write("Enter some text. ")
strTemp = Console.ReadLine()
GetInput = strTemp
End Function
The last line of the function specifies the value to be returned using the function name. An alternative to this is to use the return statement. For example,
Return strTemp
Having A Go
- Write a program that includes a function to return the largest and smallest of 3 numbers entered at the keyboard.
- Write a program that includes an IsNumberPrime() function that returns true if a number is prime and false if not. Use this program to allow the user to enter a number and find out if the number is prime.
- Write a program to read in an integer and return the binary equivalent of that number as a string.
- Write a program to read in an integer and return the hexadecimal equivalent of that number as a string.