CSI 1301 PROGRAMMING IN VISUAL BASIC PART 1. Part 1 1. Visual Basic Programming 2. Translating the...

Post on 14-Dec-2015

238 views 0 download

Transcript of CSI 1301 PROGRAMMING IN VISUAL BASIC PART 1. Part 1 1. Visual Basic Programming 2. Translating the...

CSI 1301

PROGRAMMING IN VISUAL BASIC

PART 1

Part 1

1. Visual Basic Programming2. Translating the Algorithm Declaration3. Translating Assignment Instructions4. Translating Get and Give Instructions5. Additional Material

1. Visual Basic Programming

Visual Basic Programming

Visual Basic is a programming language for Windows applications

We will use it to:– Run our algorithms on a computer

• Use the computer as the computing agent

– Assist us in making more effective use of Excel• To provide a suitable user interface in our worksheets

• To express complex logic in formulas (see the slides titled Example of Complexity in the Additional Material at the end of this lecture)

Visual Basic Programming

Creating an algorithm can be difficult– Think through the problem and solve it without using a

computer

However, with an algorithm, writing the program becomes easy– Translate the instructions in the algorithm to Visual

Basic instructions

English

ALGORITHM

Visual Basic

Visual Basic Programming

Problems encountered in developing an algorithm– Comprehension problems (“Misinterpretation”)

– Process problems (“How do I solve it?)

Problems encountered in a Visual Basic program– Syntax errors (Grammatical and spelling mistakes)

– Semantic errors (Program runs but errors in logic lead to incorrect results)

– Run time errors (Program fails when running ie. dividing by zero)

2. Translating the Algorithm Description

Translating the Algorithm DescriptionWhen a program is executing, the instructions and

data being processed are stored in RAMThe following parts of the Algorithm Description

tell us what data is to be stored and processed by our program– Givens

– Intermediates

– Results

Each data item can be either a variable or a constant

Translating the Algorithm DescriptionVariable

• Is an address in RAM that has a name and contains a value• The value can change as the code is executed• Can hold only one value at a time

Constant

• Has a value that does not change as the code is executed• A meaningful name used in place of a value

Names• Begin with a letter• Maximum of 255 characters in length• Contain only letters, numbers and _ (underscore)• Not case sensitive• Cannot be a Visual Basic reserved word

Translating the Algorithm DescriptionWe tell the Visual Basic translator what type of

data is to be processed by our program by defining data types

• Each data type determines– The kind of data which can be stored in RAM– The range of possible values– How many bytes of RAM will be used to store it– The type of operations that can be performed on the data

The Visual Basic translator can then• Determine how and where to store that data in RAM• Tell us if we try to do something silly in our program

– 15 + “joe smith” = ???– Store text in a numeric variable

Translating the Algorithm DescriptionThe Visual Basic translator keeps track of where

each data item is stored in RAMWhen we want to reference the value of a data

item, we simply use its name. The Visual Basic translator knows where to go in RAM to find the value.

Translating the Algorithm DescriptionDeclaring variables and constants in a program

– Done with a DIM statement for a variable• Also specify the data type with the As clause• Advantages

– Code is easier to read– Speeds up execution of code– Conserves memory space

– Done with a CONST statement for a constantOption Explicit must be used in the first line

– Forces all variables and constants to be declared– (also useful to detect misspelled variable and constant

names)

Translating the Algorithm DescriptionEnter OPTION EXPLICIT on the first line All programs begin with SUB and end with END

SUBComments are lines that are ignored by the

computer. – We use them to make our code easier to read– Everything to the right of a ‘ (single quote) is a comment

Look at GIVENS, INTERMEDIATES and RESULTS– Each entry must be declared– Also define the type for each variable

Translating the Algorithm DescriptionOPTION EXPLICIT

'WRITTEN BY T. JAMES

SUB myprogram ()

DIM studnum as String*7 'Student Number

DIM MT as Single 'Midterm Exam

DIM FE as Single 'Final Exam

DIM NG as Single 'Numeric Grade

CONST PI = 3.14159 'PI

END SUB

Translating the Algorithm DescriptionWhere do we enter this code?

– In the Visual Basic Editor in Excel• To open the Editor

– select Tools – Macro – Visual Basic Editor– or right click a worksheet tab and select View Code (not

recommended)– or press Alt + F11

• Then select Insert – Module• Then enter the code

The Visual Basic Editor is described in more detail in the Additional Material at the end of these lecture slides

3. Translating Assignment Instructions

Algorithmic Representation of Computer Functions Input

– Get informationStorage

– Store informationProcess

– Arithmetic operations

– Logic decisions

– Repeat instructionsOutput

– Give information

GET

Given/Results/Intermediates/Set

LET

IF

LOOP

GIVE

Assignment Instructions

An assignment statement is used to assign a value to a variableVariable = Expression

– The computed value of the Expression is assigned to (stored in) the variable on the left side of the = sign

Assignment Instructions

X = 5– Take the value of 5 and store it in X

Y = X + 3– Take the value of X (5) and add 3 to get 8– Store 8 in Y

X = X + 1– NOT AN ALGEBRAIC EQUATION– Take the value of X (5) and add 1 to get 6– Store 6 in X (replacing the value of 5)

Assignment Instructions

The order of precedence of arithmetic operators in an expression is as follows:

Brackets ()Exponents ^Division / Multiplication *Addition +Subtraction -

Translating Assignment InstructionsLook at the METHOD.

Translate any instruction with an = sign as an assignment statement

Each assignment statement is one line of code– Write each in the proper form

Variable = Expression

Translating Assignment InstructionsALGORITHM

X = 5 Y = X + 3

C = 2r A = r2

VISUAL BASIC

X = 5 Y = X + 3

C = 2 * PI * R A = PI * R^2

Translating Assignment InstructionsOption Explicit'Written by T. James

Sub Circles()Dim R as Single 'RadiusDim A as Single 'AreaDim C as Single 'Circumference

Const PI = 3.1415926

R = 1.2A = PI * R^2C = 2 * PI * R

End Sub

4.Translating Get and Give Instructions

From/To the User

GET/GIVE from/to the User

At the most basic level, our programs – get information from the user (input) via the keyboard

or mouse, and

– give information to the user (output) via the screen

Therefore, we need Visual Basic instructions to – read user input from the keyboard or mouse, and

– write information on the screen

GET from the User

An InputBox is used to get information that is entered by the user at the keyboard

Variable = InputBox(“prompt message”, “title”, “default input”, Xcor, Ycor)– Variable stores the information entered by the user

– Prompt message describes what we want the user to enter

– Title appears in the title bar at the top of the InputBox

– Default input shows a sample of the type of information to be entered

– Xcor and Ycor are the X and Y axes coordinates that position the InputBox on the screen

GET from the User

Frequently, we do not need to specify the title, default input or positioning coordinates

– Then the Visual Basic instruction to get information from the user can be simplified to

Variable = InputBox(“prompt message”) Name = InputBox(“Enter your Name”)

– When this statement is executed, an InputBox will appear on the user’s screen

– The InputBox will contain the text, Enter your Name– It will also contain a rectangle – The information entered by the user will appear in this rectangle– The InputBox will also contain an OK button– When the user has entered his/her name, he/she will click the OK button and

the information entered will be stored in the variable Name

GET from the User

Income = InputBox(“Enter your income”)– Stores what the user enters in the variable Income

GIVE to the User

A MsgBox is used to send information to the screen for the user to view– We will explore the full capabilities of the MsgBox later

For now, we can use the following statement MsgBox(“message”)

– Message is the information that will be displayed in the MsgBox on the screen

– The MsgBox will also contain an OK button– When the user has read the message, he/she will click the

OK button and the MsgBox will disappear from the screen

GIVE to the User

MsgBox(“The Tax is “ & Tax)– Takes the string “The Tax is “ and concatenates it with

the value of the variable Tax

– Displays the result on the screen in a MsgBox• Concatenation can also be accomplished with +

• Preferable to use &

Look at the METHODTranslate any GET or GIVE instructions that refer

to the user as follows.

– GIVE: MsgBox(“message”)

– GET: variable = InputBox(“prompt message”)

Translating to Visual Basic

Translate 1

Translate Algorithm 1.5– NAME: CalcMark– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total,

MaxMark (Constant)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/MaxMark * 100

• Give Mark

Option Explicit

'Written By T. James

Translate 1

Translate Algorithm 1.5– NAME: CalcMark– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total

MaxMark(Constant)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/MaxMark * 100

• Give Mark

Option Explicit

'Written By T. James

Sub CalcMark ()

Translate 1

Translate Algorithm 1.5– NAME: CalcMark

– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total

MaxMark (Constnat)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/MaxMark * 100

• Give Mark

Option Explicit

'Written By T. James

Sub CalcMark ()

Dim A1 as Integer

Dim A2 as Integer

Dim A3 as Integer

Dim Mark as Single

Dim Total as Integer

Const MaxMark =140

Translate 1

Translate Algorithm 1.5– NAME: CalcMark– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total

MaxMark (Constant)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140

• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/150 * 100

• Give Mark

Option Explicit

‘Written By T. James

Sub CalcMark () Dim A1 as Integer Dim A2 as Integer Dim A3 as Integer Dim Mark as Single Dim Total as Integer Const MaxMark = 140

A1 = InputBox("A1?")

A2 = InputBox("A2?")

A3 = InputBox("A3?")

Translate 1

Translate Algorithm 1.5– NAME: CalcMark– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total,

MaxMark (Constant)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/MaxMark * 100

• Give Mark

Option Explicit

'Written By T. James

Sub CalcMark () Dim A1 as Integer Dim A2 as Integer Dim A3 as Integer Dim Mark as Single Dim Total as Integer Const MaxMark = 140

A1 = InputBox("A1?") A2 = InputBox("A2?") A3 = InputBox("A3?")

Total = A1 + A2 + A3

Mark = Total/150 * 100

Translate 1

Translate Algorithm 1.5– NAME: CalcMark– GIVENS: A1, A2, A3– RESULTS: Mark– INTERMEDIATES: Total,

MaxMark (Constant)– DEFINITION:

• Mark := CalcMark(A1, A2, A3)– METHOD:

• Set MaxMark = 140• Get A1• Get A2• Get A3

• Let Total = A1 + A2 + A3• Let Mark = Total/150 * 100

• Give Mark

Option Explicit

'Written By T. James

Sub CalcMark () Dim A1 as Integer Dim A2 as Integer Dim A3 as Integer Dim Mark as Single Dim Total as Integer Const MaxMark = 140

A1 = InputBox("A1?") A2 = InputBox("A2?") A3 = InputBox("A3?")

Total = A1 + A2 + A3 Mark = Total/150 * 100

MsgBox("Mark is " & Mark)

End Sub

Algorithm 1.5

5. Additional Material

Example of Complexity

Visual Basic Editor

Translation Set 1

Example of ComplexityStudent Marks

B C D E F G H I J 1 # a1 a2 a3 a4 a5 m f g 2 1 10 10 10 10 10 50 40 3 2 2 5 8 3 9 60 45 4 3 8 9 7 6 10 60 70 5 4 5 5 5 5 5 50 50 6 5 10 9 8 7 6 70 48 7 6 10 6 3 9 10 76 74 8

Example of Complexity

Calculate the final mark, based on 25% forassignments, 25% for midterm and 50% forfinal examination– insert the following formula in cell j2 & copy it to the

other cells in column j=0.5*(SUM(c2:g2))+0.25*h2+0.5*i2

Variation 1– “If the student failed the final exam, then he/she fails

the course.”=IF(i2>=50,formula as above,i2)

Example of ComplexityVariation 2

– “If the student failed the final exam, then the weighted sum of 1/3 midterm mark and 2/3 final exam mark must be 50 or more for the student to pass the course.”

=IF(i2<50,IF((h2/3)+(2*i2/3)>=50,as above,i2),as above)Variation 3

– Assign letter grades to the final marks– a more complex case

» (more nesting required)– the need to write code

» (a user defined function)

Visual Basic Editor

The Visual Basic Editor– Consists of 4 windows

• Main, Code, Project Explorer, Properties

1 Main window– Title bar, menu bar & standard toolbar

2 Code window– Insert – Module

– To write code for procedures

Visual Basic Editor

3 Project Explorer window• Shows the open project (name of file containing the project)• Shows the worksheets & modules in the project (in a format

similar to Windows Explorer)• Has 3 buttons

– View Code: view the code in the module selected– View Object: view the worksheet selected– Toggle Folders: control the display of the folder

4 Properties window– To change properties for any worksheet or module– Properties control an object’s appearance & behaviour

Translation Set 1

Translate 2 Translate Algorithm 1.4

NAME:AVG3GIVENS:

Num1, Num2, Num3RESULTS:

Sum , AverageDEFINITION:

Sum & Average := AVG3(Num1, Num2, Num3)

METHOD:Get Num1Get Num2Get Num3Let Sum = Num1 + Num2 + Num3Let Average = Sum /3Give SumGive Average

Option Explicit'Written By T. JamesSub AVG3 () Dim Num1 as Integer Dim Num2 as Integer Dim Num3 as Integer Dim Sum as Integer Dim Average as Single

Num1 = InputBox("Num1?") Num2 = InputBox("Num2?") Num3 = InputBox("Num3?")

Sum = Num1 + Num2 + Num3 Average = Sum/3

MsgBox("SUM = " & Sum) MsgBox("Average = " & Average)End Sub

Algorithm 1.4

Translate 3NB Div is Implemented as \ Translate Algorithm 1.6

NAME: SumDigGIVENS: NRESULTS: SumINTERMEDIATES: Tens, OnesDEFINITION: Sum := SumDig(N)METHOD:

Get N

Let Tens = N div 10Let Ones = N mod 10Let Sum = Tens + Ones

Give Sum

Option Explicit

'Written By T. James

Sub SumDig () Dim N as Integer Dim Sum as Integer Dim Tens as Integer Dim Ones as Integer

N = InputBox("2 Dig Num?")

Tens = N \ 10 Ones = N mod 10 Sum = Tens + Ones

MsgBox("Total is " & Sum)

End Sub

Algorithm 1.6

Homework

What value is assigned to z by the statement below, assuming z, a, b, w and y have respectively the values 8, 3, 9, 2 et –5.

z = z - (a + b / 2) + w * -y

1. Write an algorithm to sum 5 numbers. Translate the algorithm into Visual Basic code

2. Write an algorithm to compute the average of 5 numbers. Translate the algorithm into Visual Basic code

3. Write an algorithm to multiply 3 numbers. Translate the algorithm into Visual Basic code

4. Write an algorithm to multiply 2 numbers and divide the product by a third number. Translate the algorithm into Visual Basic code

1. Write an algorithm to calculate the average mark out of 100, given three assignment marks, each of which is marked out of 20. Translate the algorithm into Visual Basic code

2. Write an algorithm to calculate the sum of the digits of a three digit number. Translate the algorithm into Visual Basic code

3. Write an algorithm to swap two numbers. Translate the algorithm into Visual Basic code

4. Write an algorithm to sum four numbers and return the sum in the variable x. Translate the algorithm into Visual Basic code