Thursday, May 01, 2014

Lesson 6: Functions and Procedures (vbscript)

Functions and Procedures make your code modular. They help you to keep repeated statements as blocks of code that can be reused. Both functions and procedures do the same thing, except, Functions can return value. So as a good practice never let your functions have any statements to print(display) or get input from keyboard.

Let your functions take parameters and return the value. How does a function return a value? Function_name=value you want to return. Enough of theory.

This program finds the value of (a+b) squared.

(a+b)2 =a2 +2ab+b2

‘File-0105-1.vbs (this is file name I have)

Function Sq_ab(a,b)
    sq_ab=a*a + 2*a*b + b*b
End Function

Sub Print(str)
    wscript.echo str
End Sub

'Main program starts here

a=int(wscript.arguments(0))
b=int(wscript.arguments(1))
Print("The Square of (a+b) is " & Sq_ab(a,b))

Sample Output

C:\scripts>0105-1.vbs 2 3 //nologo
The Square of (a+b) is 25

C:\scripts>0105-1.vbs 7 9 //nologo
The Square of (a+b) is 256

C:\scripts>

Exercises for you.

1. Write functions for (a-b)2, a2-b2, (a+b)3 and so on

No comments: