Introduction to VB prepared by Dr. I A Moneim Reference Book Schneider.

Slides:



Advertisements
Similar presentations
Working with Intrinsic Controls and ActiveX Controls
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
CHAPTER TWO Creating Simple Visual Basic.NET Windows Applications.
Fundamentals of Programming in Visual Basic
Fundamentals of Programming in Visual Basic
Introduction to Computing Dr. Nadeem A Khan. Lecture 8.
Introduction to Computing Dr. Nadeem A Khan. Lecture 10.
Basics of ASP.NET. 2 © UW Business School, University of Washington 2004 Outline Installing ASP.NET and Web Matrix Data Types Branching Structure Procedures.
Chapter 4 - Visual Basic Schneider
Introduction to Computing Dr. Nadeem A Khan. Lecture 7.
CVEV 118/698 Visual Basic Lecture 1 Prof. Mounir Mabsout Expert 1: Elsa Sulukdjian Expert 2: Walid El Asmar.
Introduction to Computing Dr. Nadeem A Khan. Lecture 4.
Introduction to Computing Dr. Nadeem A Khan. Lecture 4.
Introduction to Computing Dr. Nadeem A Khan. Lecture 4.
Introduction to Computing Dr. Nadeem A Khan. Lecture 17.
Introduction to Computing Dr. Nadeem A Khan. Lecture 19.
Introduction to Computing Dr. Nadeem A Khan. Lecture 11.
Introduction to Computing Dr. Nadeem A Khan. Lecture 14.
Introduction to Computing Dr. Nadeem A Khan. Lecture 6.
Introduction to Computing Dr. Nadeem A Khan. Lecture 13.
Introduction to Computing Dr. Nadeem A Khan. Lecture 18.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
To type the VB code behind the command button (named cmdPush), Double-Click on the Push Me (caption) command button As a result the Visual Basic Code Window.
Introduction to Computing Dr. Nadeem A Khan. Lecture 9.
Introduction to Computing Dr. Nadeem A Khan. Lecture 5.
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Visual Basic Chapter 1 Mr. Wangler.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
© 2006 Lawrenceville Press Slide 1 Chapter 3 Visual Basic Interface.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Input, Output, and Processing
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
Chapter 2: Using Data.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter Two Creating a First Project in Visual Basic.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Practical Programming COMP153-08S Week 5 Lecture 1: Screen Design Subroutines and Functions.
Visual Basic Programming Introduction VB is one of the High level language VB has evolved from the BASIC language. BASIC stands for Beginners All-purpose.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Introduction to Programming Fundamentals of Programming in Visual Basic.
1 Visual Basic Part I - A tool for customizing your program Principles of GIS
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Introduction to Computing Dr. Nadeem A Khan. Lecture 7.
Introduction to Computing Dr. Nadeem A Khan. Lecture 9.
Slide 1 Controls v Control naming convention –Label: lblName –Command Button: cmdName –Text Box: txtName.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Data and variables in Visual Basic. Annoucement Lecture on Thursday 7:30PM C106 Visual Basic download: 
IE 411/511: Visual Programming for Industrial Applications Lecture Notes #2 Introduction to the Visual Basic Express 2010 Integrated Development Environment.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
Introduction to Computing Dr. Nadeem A Khan. Lecture 21.
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
Egyptian Language School Computer Department
Introduction to Computing
Introduction to Computing
Variables and Arithmetic Operations
Visual Basic.
WEB PROGRAMMING JavaScript.
Sub Procedures and Functions
CS285 Introduction - Visual Basic
Introduction to Programming
Presentation transcript:

Introduction to VB prepared by Dr. I A Moneim Reference Book Schneider

Visual Basic 6 Three editions: –Learning Edition –Professional Edition –Enterprise Edition Learning Edition is enough Others can also be utilized

Integrated Development Environment Integrated Development Environment (IDE) is a place to create your applications. It is integrated because you can virtually access all of the development tools from one screen called the interface. The IDE is also called the design environment.

Components of IDE The visual basic is made up of a number of components –Menu bar –Tool bar –Project explorer –Properties window –Form layout window –Toolbox –Form design –Object browser

Menu Bar Tool Bar Form Toolbox Form Designer Project Explorer Properties Window Form Layout Window IDE

Propertie s Window

View Code View Object Toggle Folders Project Explorer

Label Control Frame Control Check Box Combo Box Horizontal Scroll Bar Timer Control Shape Object OLE Control Image Object Directory List Box Picture Box Text Box Drive List Command Button Option Button List Box Vertical Scroll Bar File List Box Line Object Data Control Toolbox

Open Project Add Module Drop-Down List Project Wizard Dropdown List Paste Cut Undo End Start Project Explorer Window Form Layout Window Toolbox Add Standard Exe Project Add Form Menu Editor Copy Save ProjectFind Redo Break Properties Window Object Browser Data View Window Toolbar

Components of IDE The visual basic is made up of a number of components –Menu bar –Tool bar –Project explorer –Properties window –Form layout window –Toolbox –Form design –etc.

Menu Bar Tool Bar Form Toolbox Form Designer Project Explorer Properties Window Form Layout Window IDE

Label Control Frame Control Check Box Combo Box Horizontal Scroll Bar Timer Control Shape Object OLE Control Image Object Directory List Box Picture Box Text Box Drive List Command Button Option Button List Box Vertical Scroll Bar File List Box Line Object Data Control Toolbox

Introducing Controls Label: To display information Textbox: To get information Command Button: To initiate action (by clicking) Picture Box: To display text or graphics

The Label Information (text) is displayed only A few properties –Name –Caption –Width –Height –Font –BackColor –ForeColor Tryout the Label Walkthrough

The Textbox Information can be typed in at run time A few properties –Name –Height –Width –Text –Font –BackColor –ForeColor –Multiline Tryout the Text Box Walkthrough

The Command Buttons For initiating an action by clicking A few properties –Name –Caption: Ampersand (&) can also be used –Width –Height –Font –BackColor Tryout the Command Button Walkthrough

The Picture Box To display text or graphics A few properties –Name –Picture –Width –Height –Autosize –BackColor Tryout the Picture Box Walkthrough

The Form Object Control menu Caption Title Bar Min Button Max/Restore Close Button Border

The Form object NameCaption WidthHeight BackColorBorderStyle LeftTop StartUpPositionMaxButton MinButtonPicture Window for designing the user interface A few properties:

Setting Properties Setting free text properties 1.Select the property 2.Type the new value 3.Press ENTER or select a different property.

Setting Enumerated Properties The ENABLED properties can only be TRUE or FALSE. There are properties that have more than 2 possible values. These are represented by ENUMERATED properties.

Example For example to select the Start up position of a Form can be selected by RIGHT CLICKING on the arrow facing downward and toggling through all the possible values.

Setting Properties with Property Pages Some properties are more complex than others. Some properties require the use of property pages to select a value from them. An ellipse appears on the right of the property if it has a property page. One such example is the FONT property.

Font Property Page

Visual Basic Events Event : Action taken by the user e.g. –Clicking a Control –Double Clicking a Control –Getting Focus –Losing Focus etc.

Visual Basic Events (Contd.) Naming of Events –Clicking a Command Button 1 Command1_Click –Double Clicking a Picture Box 2 Picture2_DblClick –Text box 1 gets Focus Text1_GotFocus –Text box 1 loses Focus Text1_LostFocus

Visual Basic Events (Contd.) Names of events => objectName_event Events are pre-defined

Event Procedure Event Procedure: block of code to be executed when an event occurs General form Sub objectName_event() statements End Sub

Event Procedure (Contd.) E.g: Sub Command1_Click() statements End Sub Sub Text1_GotFocus() statements End Sub

Sub Text1_KeyPress(KeyAscii as Integer) statements End Sub Text1_KeyPress event will occur when Text1 has the focus and a key is pressed The Keypress Event Procedure

Sub Text1_KeyPress(KeyAscii as Integer) statements End Sub Keyascii –is a variable (of type Integer) –gets the ANSI value of the pressed key –value is used to display the corresponding character in the Text1 at the end of this procedure The Keypress Event Procedure (Contd.)

What will happen in these cases? Sub Text1_KeyPress(KeyAscii as Integer) Let KeyAscii =65 End Sub Sub Text1_KeyPress(KeyAscii as Integer) Let KeyAscii =0 End Sub The Keypress Event Procedure (Contd.)

Already known: –String –Single –Integer Data Types

Strings Storage: 10 bytes + string length Range: 0 to app. 2 billions chars. Declaration: Dim strVarLen As String (declares a string of a variable length) Data Types (Contd.)

Fixed-Length Strings Storage: Length of string Range: 1 to app. 65, 400 chars. Declaration: Dim strFixLen As String * 2 (declares a string of a fix size of 2 chars.) Data Types (Contd.)

Fixed-Length Strings Usage: Example Dim strText As String * 5 Let strText = “ Hello ” Picture1.Print strText Let strText = “ H ” Picture1.Print strText Let strText = “ HelloWorld ” Picture1.Print strText Data Types

Fixed-Length Strings Usage: Result: Hello(Complete string) H …. (H followed 4 spaces) Hello(First 5 characters only) => The length is fix Data Types

Integers Storage: 2 bytes Range: -32,768 to 32,767 Declaration: Dim intExample As Integer (declares intExample as an Integer variable) Data Types (Contd.)

Integers Usage: Example Dim count As Integer Let count= 6 Picture1.Print count Let count= count+1 Picture1.Print count Let count= 6/5 Picture1.Print count Let count= * 2 Picture1.Print count Data Types

Integer Usage: Result (rounding to lower value) 5(rounding to higher value) => takes only whole number values Data Types

Long (Integer) Storage: 4 bytes Range: -2,147,483,648 to 2,147,483,647 Declaration: Dim lngExample As Long (declares lntExample as a long variable) Data Types (Contd.)

Long (Integer) Usage: Same as Integer Type except the range is much larger Data Types (Contd.)

Byte Storage: 1 byte Range: 0 to 255 Declaration: Dim bytExample As Byte (declares bytExample as a Byte type variable) Data Types (Contd.)

Byte Usage: Same as Integer Type except the range is positive and much smaller Data Types (Contd.)

Boolean Storage: 2 bytes Range: TRUE(1) or FALSE(0) Declaration: Dim blnState As Boolean (declares a Boolean type variable blnState) Data Types (Contd.)

Boolean Usage: Example Dim blnExample As Boolean Let blnExample= FALSE Picture1.Print blnExample Let blnExample= 1 Picture1.Print blnExample Let blnExample= 6 Picture1.Print blnExample Let blnExample= -8*7+5.2 Picture1.Print blnExample Data Types (Contd.)

Boolean Usage: Example FALSE TRUE =>Values other than 0 are TRUE Data Types (Contd.)

Single (Precision Floating-Point) Storage: 4 bytes Range: -3.4 … E38 to -1.4 … E-45 (negative) 1.4 … E-45 to 3.4 … E38 (positive) Declaration: Dim sngAverage As Single (declares a Single type variable sngAverage) Data Types (Contd.)

Double (Precision Floating-Point) Storage: 8 bytes Range: -1.7 … E308 to -4.9 … E-324 (negative) 4.9 … E-324 to 1.7 … E308 (positive) Declaration: Dim dblAverage As Double (declares a Double type variable dblAverage) Data Types (Contd.)

Double Usage: Example Dim sngValue As Single, dblValue As Double Let sngValue= 1/3 Picture1.Print sngValue Let dblValue= 1/3 Picture1.Print dblValue Data Types (Contd.)

Double Usage: Result (Single precision) (Double precision) => Value of 1/3 represented more accurately by double than by single Data Types (Contd.)

Double Usage: Example Dim sngValue As Single, dblValue As Double Let sngValue= 1/3 Let sngValue= sngValue * Picture1.Print sngValue Let dblValue= 1/3 Let dblValue= dblValue * Picture1.Print dblValue Data Types (Contd.)

Double Usage: Result (Single precision; rounding error) (Double precision) => - The decimal point is floating; - Eventually both will be subjected to rounding errors value increases to large values - Still Double will remain more precise than Single Data Types (Contd.)

Currency Storage: 8 bytes Range: -922,337,203,685, to 922,337,203,685, Declaration: Dim curRevenue As Currency (declares a Currency type variable curRevenue) Data Types (Contd.)

Currency Usage: Example Dim curValue As Currency Let curValue= 1/3 Picture1.Print curValue Let curValue= 100*1/3 Picture1.Print curValue Data Types (Contd.)

Currency Usage: Result =>- The decimal point is NOT floating; - Could be used for currency and scientific research - No rounding problems for high values Data Types (Contd.)

Even more data types –Date Variable: for date and time –Object Variable –Variant Variable –………. Read the book for more info. Data Types (Contd.)

Not only +,-,*,^ But also: \ opeartor e.g: 5.1\2.04= 2 MOD operator e.g: 15.2 MOD 6=3 More on Operators

More on Operators (Contd.) Operator Precedence 1. ^ 2.- operator (indicating a negative value) 3. * and / operator 4. \ operator 5. MOD operator 6. + and - operator

Statements?

VB Statements Statements to change the properties of an object the general form: Let objectName.property = setting

Statements (Contd.) Let objectName.property = setting E.g: Let Text1.FontSize = 12 Let Text1.FontBold = TRUE Let Text1.Text = “ ”

Event Procedure (Contd.) Event procedure – general form Sub objectName_event() statements End Sub Example Sub Command1_Click() Let Text1.text = “” Let Text2.text= “ Hello ” End Sub

Viewing Code Margin Indicator Bar Procedure View Full Module View Object Box Procedures List Box Split Bar

Methods Another category of statements based on methods

Methods (Contd.) E.g: –Picture1.Cls Clears Picture1 Picture Box –Picture1.Print 3 Prints ‘ 3 ’ in the Picture1 Picture Box

Methods (Contd.) General form of these statements => objectName.Method parameters (if any)

The Print Method Picture1.Print m? Picture1.Print m; ? Picture1.Print m; n; r ? m, n, r are numbers e.g. 3, 5.2

Numbers Numeric Constants – 2, 5.6, 9, Arithmetic Operations –Addition (2+3) –Subtraction (2-3) –Multiplication (2*3) –Division (2/3) –Exponentiation (2^3)

Numbers (Contd.) Numeric Expressions e.g. –(2+3)/5 –(5+2) * (2- 10/2) –2.5*2-3^2+14/7

Numbers (Contd.) How will this be calculated? –2+10/5 –5+2* 2- 1/10 –4*6-3^2+5/10 –3^2*5

Numbers (Contd.) Operator Precedence 1. ^ 2.- operator (indicating a negative value) 3. * and / operator 4. + and - operator

Numbers (Contd.) Use parenthesis ( ) to keep intentions clear (2+2)*2? 2+2*2? (5+ (5*2))/(2+1) ?

Strings E.g: –“ hello ” –“ 9/17/95 ” –“ 2+3 ”

What will be printed? Picture1.Print 2*3+2 Picture1.Print “ hello ” Picture1.Print “ 2*3+2 ”

Scientific Notation E=Exponent => Exponent of 10 E.g. – 1.2E+04 = 1.2 * 10^4 = – 1.2E+34 = 1.2 * 10^34 –1E-02 = 1 * 10^-2 =.01

Scientific Notation (Contd.) Display notation (Scientific or Standard) depends on magnitude

What this code will do? Let num1 = 6 Picture1.Print num1

Variables (Contd.) Conclusions: A variable holds a value The value can be assigned and then used

Variables (Contd.) What will this code do? Let result = 100*4 Picture1.Print result

Variables (Contd.) What will this code do? Let speed=50.3 Let timeElapsed =2 Let distance = speed*timeElapsed Picture1.Print distance

Variables (Contd.) Conclusions: The General Form: Let var = expression e.g.: Distance=speed*timeElapsed c= a*(2.2+b)+6 counter=counter+1

String Variables Sub Command1_Click () Picture1.Cls Picture1.Print “ hello ” Let today = “ 9/17/95 ” Let message = “ students of CS101 ” Picture1.Print today Picture1.Print “ hello ” ; message End Sub

String Variables (Contd.) Result: hello 9/17/95 hellostudents of CS101

String Variables (Contd.) Concatenation (use + or &) Sub Command1_Click () Picture1.Cls Let message_part1 = “ hello ” Let message_part2 = “ students of CS101 ” Let message= message_part1+message_part2 Picture1.Print message Picture1.Print message + “ on Sept. 19,2002 ” Let message= message_part1 & “ world ” Picture1.Print message End Sub

String Variables (Contd.) Displayed Result hellostudents of CS101 hellostudents of CS101 on Sept. 19,2002 hello world

Declaring Variable Types Dim var As String Dim var As Single

Declaring Variable Types (Contd.) Example program: Sub Command1_Click () Dim interestRate As Single Dim principal As Single Dim phrase as String Picture1.Cls Let InterestRate=.0655 Let principal =100 Let phrase = “ The balance after a year is ” Picture1.Print phrase;(1+interestRate)*principal End Sub

Declaring Variable Types (Contd.) Displayed Result: The balance after a year is

Declaring Variable Types (Contd.) Different ways of declaration –Dim interestRate As Single, principal As Single, phrase As String –Dim name$ (same as Dim name As String) –Dim price! (same as Dim price As Single) –Use the type declaration tag while using it E.g.: Let name$ = “ John ” Let price! = 65.66

Input/Output Using Text Box Contents of a text box is always a string Output the string by –Let Text1.Text= strvar Input the string by –Let strVar =Text1.Text

Input/Output Using Text Box (Contd.) Numbers in a textbox are also stored as strings Input a number by –Let numVar = Val(Text1.Text) Output a number by –Let Text1.Text=Str$(numVar)

Another example: Sub Command1_Click() Picture1.Cls Let rate = 50 Let timeElapsed = 14 Let distance = rate * timeElapsed Picture1.Print distance Let distance = 410 Let timeElaspsed = distance / rate Picture1.Print timeElapsed End Sub

Built-in Functions Take one or more input values Return an output value Already seen: –Val(..), Str$(..), Asc(..), Chr(..)

Built-in Numeric Functions Sqr: calculates square-root and returns the value as double data type e.g: –Sqr(9) is 3 –Sqr(0) is 0 –Sqr(2) is –Sqr(30*2+4) is 8

Built-in Numeric Functions Int: Greatest integer less than and equal to a number e.g: –Int(2.7) is 2 –Int(3) is 3 –Int(-2.7) is -3

Built-in String Functions Left$, Mid$, Right$, UCase$, Trim$ Left$( “ fanatic ”, 3) is “ fan ” Right$( “ fanatic ”, 3) is “ tic ” Left$( “ 12/15/93 ”,2) is “ 12 ” Right$( “ 12/15/93 ”, 2) is “ 93 ” Mid$( “ fanatic ”, 5,1) is “ t ” Mid$( “ 12/15/93 ”,4, 2) is “ 15 ” Ucase( “ Disk ” ) is “ DISK ” Ucase( “ 12two ” ) is “ 12TWO ” Trim$( “ 1 2 ” ) is “ 1 2 ” Trim$( “ -12 ” ) is “ -12 ”

Built-in Functions (Contd.) Len Len( “ Shenandoah ” ) is ? Len( “ Just a moment ” ) is ? Len( “ m ” ) is ?

Built-in Functions (Contd.) Len Len( “ Shenandoah ” ) is 10 Len( “ Just a moment ” ) is 13 Len( “ m ” ) is 1

Built-in Functions (Contd.) Instr Instr( “ Shenandoah ”, “ nand ” ) is ? Instr( “ Just a moment ”, “ ” ) is ? Instr( “ Croissant ”, “ ist ” ) is ?

Built-in Functions (Contd.) Instr Instr( “ Shenandoah ”, “ nand ” ) is 4 Instr( “ Just a moment ”, “ ” ) is 5 Instr( “ Croissant ”, “ ist ” ) is 0

Built-in Functions (Contd.) Format$ Format$(num, fmt) num: number, numeric expression, string of a number fmt: format string Result => String consisting of a formatted version of the number

Built-in Functions (Contd.) FunctionString Value Format$( , “ Standard ” )12, Format$( , “ Currency ” )$12, Format$(-1234, “ Standard ” )-1, Format$(-1234, “ Currency ” )($1,234.00) =>Result: two digits after decimal; Commas every three places to the left of the decimal point; leading ‘ $ ’ sign for currency

Built-in Functions (Contd.) FunctionString Value Format$(1/4, “ Standard ” )? Format$( “.2 ”, “ Currency ” )? Format$( , “ Currency ” )?

Built-in Functions (Contd.) FunctionString Value Format$(1/4, “ Standard ” )0.25 Format$( “.2 ”, “ Currency ” )$0.20 Format$( , “ Currency ” )($1,234.80)

Built-in Functions (Contd.) FunctionString Value Format$( , “ #,0 ” )12,346 Format$(-3.6, “ #,0 ” )-4 =>Result: Rounded; Commas every three places to the left of the decimal point

Built-in Functions (Contd.) FunctionString Value Format$(123.82, “ #,0 ” )? Format$(-3.2, “ #,0 ” )?

Built-in Functions (Contd.) FunctionString Value Format$( , “ Percent ” ) % =>Result: Multiplied by 100; trailing % sign; two digits after decimal

Built-in Functions (Contd.) FunctionString Value Format$(.06265, “ Percent ” )? Format$(1/8, “ Percent ” )?

Built-in Functions (Contd.) FunctionString Value Format$(.06265, “ Percent ” )6.27% Format$(1/8, “ Percent ” )12.50%

Built-in Functions (Contd.) FunctionString Value Format$( , “ Scientific ” )1.23E+04 =>Result: first number between 1 and 9.99 and of two digits after decimal; Exponent value preceded by E and sign;

Built-in Functions (Contd.) FunctionString Value Format$( , “ Scientific ” )? Format$(1/8, “ Scientific ” )?

Built-in Functions (Contd.) FunctionString Value Format$( , “ Scientific ” )-6.00E+02 Format$(1/8, “ Scientific ” )-1.25E-01

Built-in Functions (Contd.) Formatting dates: FunctionString Value Format$( “ 7/4/96 ”, “ Long Date ” )Thursday, July 4, 1996 Format$( “ 7/4/96 ”, “ Medium Date ” ) 04-Jul-96

Built-in Functions (Contd.) Fixed length string formatting: FunctionString Value Format$( , “ ” )? Format$(123, “ ” )? Format$( “ ”, “ ” )? Format$( “ $1, ”, “ ” )? Format$(1/4, “ ” )?

Generating Random Numbers The function: Rnd Generates a random number from 0 up to but not including 1 Picture1.Print Rnd ‘ print a different number each time Let numvar= Rnd ‘ a random value is assigned

Generating Random Numbers (Contd.) The function: Rnd Display numbers from the set {1,2,3,4,5,6} randomly!

Generating Random Numbers (Contd.) The statement: Randomize Timer?

Generating Random Numbers (Contd.) The statement: Randomize Timer Sub Command1_Click ( ) Rem Display a lottery number Picture1.Cls Randomize Timer Picture1.Print Int(10*Rnd); Picture1.Print Int(10*Rnd) End Sub

Built-in Functions (Contd.) Abs(10) is 10 Abs(-10) is 10 Sgn(10) is 1 Sgn(0) is 0 Sgn(-10) is -1

Subprograms /Subroutines

Subprograms (Contd.) General Format Sub SubprogrammeName (list of parameters) statements End Sub

Subprograms (Contd.) Example 1 Sub ExplainPurpose ( ) Rem Explain the task performed by the program Picture1.Print “ This program displays sentences ” Picture1.Print “ identifying pairs of numbers and their sums. ” End Sub

Subprograms (Contd.) Example 2 Sub Add ( num1 As Single, num2 As Single ) Rem Display numbers and their sum Picture1.Print “ Sum of ” ; num1; ” and ” ; num2; ” is ” ; num1+num2 End Sub

Subprograms (Contd.) Examples: Sub ExplainPurpose ( ) Rem Explain the task performed by the program Picture1.Print “ This program displays sentences ” Picture1.Print “ identifying pair of numbers and their sums. ” End Sub Sub Add ( num1 As Single, num2 As Single ) Rem Display numbers and their sum Picture1.Print “ Sum of ” ; num1; “ and ” ; num2; “ is ” ; num1+num2 End Sub

Subprograms (Contd.) Using subprograms in a Program Sub Command1_Click( ) Rem Display the sum of several pairs of numbers Picture1.Cls Call ExplainPurpose Picture1.Print Call Add(2, 3) Call Add(4, 6) Call Add(7, 8) End Sub

Subprograms (Contd.) The Program ’ s result This program displays sentences identifying pair of numbers and their sums. Sum of 2 and 3 is 5 Sum of 4 and 6 is 10 Sum of 7 and 8 is 15

Subprograms (Contd.) Using subprograms in a Program Sub Command1_Click( ) Dim x As Single, y As Single, z As Single Picture1.Cls Let x = 2 Let y = 3 Call Add(x,y) Call Add(x+2, 2 * y) Let z = 7 Call Add(z, z+1) End Sub

Subprograms (Contd.) The Program ’ s result This program displays sentences identifying pair of numbers and their sums. Sum of 2 and 3 is 5 Sum of 4 and 6 is 10 Sum of 7 and 8 is 15

Subprograms (Contd.) Writing subprograms for a Program Sub Command_Click( ) Dim x As Single, y As Single, z As Single Picture1.Cls Call ComputeWage( “ Aslam ”, 5, 100) Call ComputeWage( “ Saleem ”, 6, 90) End Sub Result: Wage of Aslam is Rs. 500 Wage of Saleem is Rs. 540

Subprograms (Contd.) The Subprogram ComputeWage: Sub ComputeWage(Name As String, hourlyRate As Single, hours As Single) Rem Compute and displays employees wage Dim wage As Single wage = hourlyRate*hours Picture1. Print Name; ” wage is ” ; wage End Sub

Note: Read: Schneider (Section 4.1) Read Comments in Section 4.1 Do practice problems 4.1 Attempt questions of Exercise 4.1

Subprograms: Passing Variables Example 1: Subroutine Sub Triple( num As Single) Rem Triples a number Picture1.Print num; Let num = num*3 Picture1.Print num; End Sub

Subprograms: Passing Variables Example 1: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple(amt) Picture1.Print amt End Sub

Subprograms: Passing Variables Example 1: Result => Variable was passed by reference in Example 1

Variable Passing by Val!

Subprograms: Passing Variables Example 2: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple((amt)) ‘ extra parentheses Picture1.Print amt End Sub

Subprograms: Passing Variables Example 2: Result => Variable was passed by value in Example 2

Subprograms: Passing Variables Example 3: Subroutine Sub Triple( ByVal num As Single) Rem Triples a number Picture1.Print num; Let num = num*3 Picture1.Print num; End Sub

Subprograms: Passing Variables Example 3: Program Sub Command1_Click( ) Dim amt As Single Picture1.Cls Let amt=2 Picture1.Print amt; Call Triple(amt) Picture1.Print amt End Sub

Subprograms: Passing Variables Example 3: Result => Variable was passed by value in Example 3 By default: Variable passing by reference To be precise you may use ByRef as in: Sub Triple( ByRef num As Single)

Subprograms: Local Variables Example 1 Sub Command1_Click( ) Picture1.Cls Call Three End Sub Sub Three( ) Dim num As Single Picture1.Print num Let num=3 Picture1.Print num End Sub

Subprograms: Local Variables Example 1: Result 0 3 => The variable num is local to the Subprogram; Lives only for the time the Subprogram is called; Initialized each time

Subprograms: Local Variables Example 2 Sub Command1_Click( )Sub Trivial ( )Dim x As Single Picture1.ClsPicture1. Print x; Let x = 2Let x = 3Picture1.Print x; Call TrivialEnd Sub Picture1.Print x; Call Trivial Picture1.Print x; End Sub

Subprograms: Local Variables Example 1: Result => The variable x has separate identities in the Event procedure and in the subroutine

Subprograms: Form-Level Variables Example 1 Dim num1 As Single, num2 As Single Sub Command1_Click( )Sub AddAndIncrement ( ) Let num1 =2Picture1.Print num1+num2 Let num2 =3Let num1= num1+1 Picture1.ClsLet num2=num2+1 Call AddAndIncrementEnd Sub Picture1.Print Picture1.Print num1 Picture1.Print num2 End Sub

Example 1: Result => The variable num1 and num2 known to all subprograms Subprograms: Form-Level Variables

Example 2 Dim pi As Single Sub Form_Load( ) Let pi = End Sub Sub Command1_Click ( ) Picture1.Cls Picture1.Print “ Circle area is: ” pi*5^2 End Sub

Example 2: Result Circle area is: => The variable pi is initialized in Form_load event Subprograms: Form-Level Variables

Functions

General Format : Subroutine Sub SubprogrammeName (list of parameters) statements End Sub General Format : Functions Sub FunctionName (list of parameters) As datatype statements FunctionName = expression End Function

Functions Examples: Function FtoC (t As Single) As Single FtoC = (5/9)*(t-32) End Function Function FirstName$ (nom As String) Dim firstSpace As Integer Rem Extract the first name from the full name nom Let firstSpace = Instr(nom, “ ” ) FirstName$ = Left$(nom, firstSpace-1) End Function

Functions Using function in a program Sub Command1_Click Dim x As Single Picture1.Print FtoC(212) x = FtoC(32) Picture1.Print x x = FtoC(81+32) Picture1.Print x End Sub

Functions (Contd.) Result:

Practice Problem Function Cider (g As Single, x As Single) As Single Cider=g*x End Function Sub DisplayNumOfGallons(galPerBu, apples As Single) Picture1.Cls Picture1.Print “ You can make ” ; Cider(galPerBu, apples); Picture1.Print “ gallons of cider. ” End Sub Sub GetData (gallonsPerBushel As Single, apples As Single) Let gallonsPerBushel =3 Let apples =9 End Sub Functions (Contd.)

Practice Problem Sub Command1_Click Rem How many gallons of apple cider can we make Dim gallonsPerBushel As Single, apples as Single Call GetData(gallonPerBushel, apples) Call DisplayNumOfGallons(gallonsPerBushel, apples) End Sub

Functions (Contd.) Practice Problem: Result You can make 27 gallons of cider

Modular Design Top-Down Design Structured Programming –Sequences –Decisions –Loops

Note: Read: Schneider (Section 4.2,4.3, 4.4) Read comments and do practice problems of these sections Attempt questions of Exercises