Sunday, 23 February 2014

Subroutines and Functions

We use proceduresie, subroutines and functions to create modular programs. Visual Basic statements are grouped in a block enclosed by Sub, Function and matching End statements. The difference between the two is that functions return values, subroutines don't.
A procedure (subroutines and function) is a piece of code in a larger program. They perform a specific task. The advantages of using procedures(subroutines and functions) are:
  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Reuse of code
  • Information hiding

Subroutines

A subroutines is a block of Visual Basic statements inside Sub, End Sub statements. Subroutines do not return values.
Option Strict On


Module Example

    Sub Main()
       
        SimpleSubroutine()
        
    End Sub
    
    Sub SimpleSubroutine()
        Print ("Simple subroutines")
    End Sub
    
End Module
This example shows basic usage of subroutines. In our program, we have two subroutines. The Main() procedure and the user defined SimpleSubroutines(). As we already know, the Main() subroutines is the entry point of a Visual Basic program.
SimpleSubroutines()
Each procedure has a name. Inside the Main() procedure, we call our user defined SimpleSubroutine() procedure.
Sub SimpleSubroutine()
    Console.WriteLine("Simple procedure")
End Sub



Procedures can take optional parameters.

 
Option Strict On

Module Example

    Sub Main()

        Dim x As Integer = 55
        Dim y As Integer = 32
       
        Addition(x, y)
        
    End Sub
    
    Sub Addition(ByVal k As Integer, ByVal l As Integer)
        Print(k+l)
    End Sub
    
End Module
In the above example, we pass some values to the Addition() procedure.
Addition(x, y)
Here we call the Addition() procedure and pass two parameters to it. These parameters are two Integer values.
Sub Addition(ByVal k As Integer, ByVal l As Integer)
    Print(k+l)
End Sub



Functions

A function is a block of Visual Basic statements inside Function, End Function statements. Functions return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Visual Basic language. There are various mathematical, string , Date and time functions.

Option Strict On


Module Example

    Dim x As Integer = 55
    Dim y As Integer = 32
    
    Dim result As Integer

    Sub Main()

        result = Addition(x, y)
        Print (Addition(x, y))
        
    End Sub
    
    Function Addition(ByVal k As Integer,ByVal l As Integer) As Integer
        Return k+l
    End Function
    
End Module
Two values are passed to the function. We add these two values and return the result to the Main() function.
result = Addition(x, y)
Addition function is called. The function returns a result and this result is assigned to the result variable.












No comments:

Post a Comment