Visual Basic 2010 (Console) Guide
Procedures
Copy and compile the following program. This program contains a procedure called AddUpNums. This procedure has two parameters, values that are sent to the procedure when it is called.
Sub AddUpNums(ByVal a As Integer, ByVal b As Integer)
Dim total As Integer = a + b
Console.WriteLine("{0} + {1} = {2}", a, b, total)
End Sub
Sub Main()
Dim one As Integer, two As Integer
Console.Write("Enter your first number. ")
one = Console.ReadLine()
Console.Write("Enter your second number. ")
two = Console.ReadLine()
Console.WriteLine()
AddUpNums(one, two)
Console.ReadLine()
End Sub
Once defined, the procedure becomes another type of statement that can be used over and over again with different parameters.
Structured Programming With Procedures
Procedures can be defined for any set of statements in our program that we want to reuse. It can also be used to help us divide our program into subtasks. This allows us to keep our programming logic organised, making it easier to locate errors and expand the program.
The diagram below is a hierarchy chart describing the structure of a program we want to write. The problem breaks down into 4 task blocks (shown on the second row of the diagram). Each of these will be written as a procedure in the actual program.
Dim num1 As Integer, num2 As Integer
Dim sum As Integer, product As Integer
Sub Main()
ReadInput()
CalculateResult()
OutputResult()
WaitForInput()
End Sub
Sub ReadInput()
Console.Write("Enter your first number. ")
num1 = Console.ReadLine()
Console.Write("Enter your second number. ")
num2 = Console.ReadLine()
End Sub
Sub CalculateResult()
sum = num1 + num2
product = num1 * num2
End Sub
Sub OutputResult()
Console.WriteLine("{0} + {1} = {2}", num1, num2, sum)
Console.WriteLine("{0} x {1} = {2}", num1, num2, product)
End Sub
Sub WaitForInput()
Console.WriteLine()
Console.WriteLine("Press Enter to continue")
Console.ReadLine()
End Sub
This is the first sample program we have written that uses global variables. Notice that the variable declarations are outside of the Sub Main and other procedures (but inside the Module..End Module). These variables can be accessed from anywhere within the program.
The Sub Main of this program consists of a series of procedure calls. All of our programming logic is grouped by its role in solving our problem. This makes the program easier to read (fewer statements in the main block) and easier to debug and alter.
Having A Go
- Adapt the first program above to include procedures for all standard arithmetic operations.