DEV1 2024 Module 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

MODULE 5: VISUAL BASIC 2005 (CONSOLE APPLICATION): AN INTRODUCTION

Outcomes

On completion of this module all learners should be able to


• Use the Visual Basic 2005 (Console Application) IDE
• Describe the various files that make up a VB console application
• Create and save an application with the correct name in a specified folder
• Understand the difference between design time, break time and run time
• Write Visual Basic 2005 (Console Application) program statements for all of the instructions used in
pseudocode
• Be able to identify compilation, runtime and logic errors
• Use the debug tool to trace the flow of program execution and examine the contents of variables

CREATING A CONSOLE APPLICATION IN VISUAL BASIC 2005

An application in Visual Basic 2005 consists of solutions, projects and files.


A solution contains all of the projects and files for the application.
A project contains the files for a specific part of the solution.
We will only have one project for each solution in Development Software 1.

The program source code in a Console Application is placed in procedures in a module file.
The ‘start-up’ procedure (i.e. the one that will be executed first) is usually called Sub Main()

All of the folders and files created for a solution are stored permanently on an external storage device
(hard disk/flash disk, etc.), so that you can review the source code, change the code or run the program
whenever you want to.

To create a new console application:

1. Start Visual Studio as follows:


a. Click START on the Windows taskbar and point to ALL PROGRAMS
b. Point to MICROSOFT VISUAL STUDIO 2005 and then click MICROSOFT VISUAL STUDIO 2005
or, if your desktop contains an icon for MICROSOFT VISUAL STUDIO 2005:
a. Double click on the icon
- The copyright screen appears briefly and then the Visual Studio Startup window opens.

2. Click TOOLS on the menu bar, then OPTIONS. Click PROJECTS AND SOLUTIONS and do the
following:
a. select SAVE NEW PROJECTS WHEN CREATED
* This ensures that a new project is automatically saved to external storage when you create it.
b. select ALWAYS SHOW SOLUTION
c. deselect SHOW OUTPUT WINDOW WHEN BUILD STARTS
d. Click OK

3. Click FILE on the menu bar, click NEW PROJECT

4. Click VISUAL BASIC in the ‘Project Types’ window on the left and CONSOLE APPLICATION in the
‘Templates’ window on the right.
a. In the NAME text box type the name of your project (usually the prac number)
b. Click on the BROWSE button next to the LOCATION text box and find the folder (usually on your
network drive) in which you want to save the project
c. In the SOLUTION NAME text box type the name of your solution (usually the same name as the
name used for the project, e.g. the prac number)
d. Select CREATE DIRECTORY FOR SOLUTION
e. Click OK
DEVELOPMENT SOFTWARE 1 MODULE 5 Page 1 of 11
Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
VB now creates a solution to which it adds a project and a module (usually called Module1) and it shows
the names of the solution, the project and the module (and other information about the project) in the
Solution Explorer Window.

A folder containing subfolders and files is saved at the location you specified (use Windows Explorer or
My Computer to see them).
e.g. If I called my solution and project prac01 , the following subfolders and files are saved:

prac01
prac01
bin
debug
My Project
Assembly files
obj
debug
Module1.vb
prac01.vbproj
prac01.sln

The solution file (ending in .sln) is the one which you open in order to change or run the program.

*NB* Do not delete any of these files/change file names etc. If you want to restart the application, delete
the whole folder.
DEVELOPMENT SOFTWARE 1 MODULE 5 Page 2 of 11
Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
To open an existing application:

1. Start Visual Studio

2. Click FILE on the menu bar, click OPEN PROJECT


or Click on the OPEN PROJECT icon
Find the drive/folder/sub folder where you saved the application and double click on the solution file
(file extension is .sln)
or Click on the solution name if it is shown in the Recent Projects list on the Visual Studio Start Page.

*NB* It is NOT good practice to open a VB solution from within My Computer or Windows Explorer.
If one of the latter two products is open when you are working in VB, there will be less temporary
workspace available for your VB solution. Sometimes this results in files being lost.
For the same reasons, it is not advisable to have any other software open (i.e. showing in the task
bar at the bottom of the screen) while you are using a product like Visual Studio.

To type the source code for your program

In the Solution Explorer window, make sure that the Module1.vb file is selected.

Make sure that the Code Editor Window (with the Module1.vb tab) is being displayed in the left half of the
screen.
If it is not, click on VIEW in the menu bar and then click on CODE (or click on the View Code icon in the
Solution Explorer window).

The Code Editor automatically adds the code required to identify the beginning and end of the module
(called Module1) and the beginning and end of the procedure (called Main).
i.e.
Module Module1

Sub Main()

End Sub

End Module

All of your code must be input in the Main procedure.


Place the cursor on the line between Sub Main() and End Sub and start typing.
Type one Visual Basic instruction per line.
Press ‘enter’ to go to a new line.

*NB* DO NOT DELETE ANY OF THE CODE THAT IS AUTOMATICALLY INSERTED BY THE EDITOR

The Code Editor automatically indents instructions and displays the Visual Basic keywords in a different
colour. “Keywords are words which have a special meaning in a programming language” (Zak, 2007:69)

Intellisense:
The Code Editor’s Intellisense feature often displays a list of choices as you are typing. Instead of typing
it yourself, you can select one of the choices by selecting it and pressing ‘enter’.

To save your solution:

Click FILE then SAVE ALL


or Click on the SAVE ALL icon.

* NB * : When you are typing in instructions, you should save on a regular basis.
This is so that you will not lose too much work if there is a power failure/network failure, etc.

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 3 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
To run your program:

Click DEBUG then START DEBUGGING


Or Press the F5 key
Or Click the START DEBUGGING ICON (the green arrow)

When you run the program, the source code is first compiled into object code and then the instructions
are executed. The object code is saved in a file with the same name as the solution and the .exe
extension. This is known as the ‘executable’ file. When you give a program to a user, you usually only
give him/her the executable file – there is no need for the user to have the source code.

To close your solution:

Click FILE then CLOSE SOLUTION

DEBUGGING YOUR PROGRAM

There are 3 main types of errors that occur in programs:

1. Syntax errors
These are usually caused by typing mistakes or incorrect use of the language.
The Code Editor usually detects these errors by placing a curly blue line beneath them.
When you place your mouse pointer on the line of code, a box is displayed which explains the error.

If you do not correct the syntax errors before you run the program, the compiler will not be able to
build the executable file and you will see the following message on your screen when you try to run
the program:

There were build errors. Would you like to continue and run the
last successful build?

When you click on NO, an Error List window is displayed at the bottom left of the screen in which all of
your ‘compilation’ errors are listed. If you double-click on the error description, the line of the code
which contains the error is highlighted in the Code window.

2. Run time errors


These are errors which occur when the program is running and an instruction cannot be executed.
They are usually called exceptions in Visual Basic.
The program stops on the instruction that cannot be executed and an error description in shown in the
IMMEDIATES window at the bottom of the screen.
The instruction is highlighted and a box explaining the error is displayed.
To stop running the program:
Click DEBUG then STOP DEBUGGING
Or Click the STOP DEBUGGING ICON
e.g.
a. if you have a instruction in which you attempt to divide a number by 0 you will get an Overflow
Exception at run time.
b. if you attempt to assign character data to a numeric variable, you will get a Cast Exception at run
time.

3. Logic errors
These are errors in the actual logic of the program, i.e. the program runs but does not produce the
expected result.

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 4 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
You can use the VB Debug Tool to trace the flow of execution of your program to help you to identify
the instruction which is causing the error.

To trace your VB program:

a. Set a breakpoint on the first line of code after the declare statements:
Right click in the grey area to the left of the instruction or click on the instruction then click DEBUG
then TOGGLE BREAKPOINT.
A brown circle should appear to the left of the instruction and the instruction should be highlighted
in brown.
b. Start running the program.
c. Execution will pause on the instruction on which the breakpoint has been set.
This instruction (now highlighted in yellow) has not been executed yet.
d. Click DEBUG then WINDOWS then AUTOS so that the values in your variables and constants
will be displayed (in a window at the bottom of the screen) while you are tracing.
In the Autos Window you should see the current value in each variable.
e. Press the F10 key.
The previously highlighted instruction is now executed and execution pauses again before the next
instruction is executed.
To display the console window click on the “Prac nn (running)” command in the task bar.
To return to the IDE in order to move to the next instruction (by pressing F10) click on the
command “File nnn” in the task bar.
Watch how the values in the variables change as each instruction is executed.
f. Continue to step through the program by pressing F10 until the program ends (after End Sub has
been executed).
Or Stop debugging at any time by clicking DEBUG then STOP DEBUGGING.

To stop tracing your program (i.e. to stop your program pausing on each instruction when you run it),
click DEBUG then DELETE ALL BREAKPOINTS

Design Time, Break Time and Run Time


- When you are creating a solution and typing in/modifying the source code, it is known as DESIGN
TIME, i.e. the program is not actually running yet.

- When you are actually running/executing the program, it is known as RUN TIME.

- BREAK TIME is when program execution pauses because of a compilation or runtime error or when
execution pauses because you have set a breakpoint and are tracing your code.

RULES FOR NAMING VARIABLES AND CONSTANTS (in Visual Basic 2005):

1. Names must start with an alphabetic character or the underscore character _

2. Names may not contain any spaces.

3. Names may only contain the characters of the alphabet, the digits 0 to 9, or the underscore
character _

4. Upper and lowercase are not treated as different characters


e.g. The following will be treated as the same variable names:
averageMark and averagemark
FinalSum and finalSum
SUM2 and sum2

5. Names should not be longer than 32 characters.

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 5 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
VISUAL BASIC (CONSOLE APPLICATION) INSTRUCTIONS: SYNTAX AND RULES

1. DATA TYPES
There are many different data types, but we will use the following in Development Software 1:

STRING
- text/character data: from 0 to 2 billion characters

INTEGER
- whole number: from -2, 147, 483, 648 to 2, 147, 483, 648

SINGLE
- floating-point number (‘real’): from 1.401298E-45 to 3.402823E38

These may be used later in the course:

LONG
- whole number: from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808

DOUBLE
- floating-point number (‘real’): from 4.9405645841247E-324 to 1.79769313486231E308

BOOLEAN
- logical value: True or False

2. DECLARATIONS:
- All declarations for variables and constants must be placed at the beginning of the code, immediately
after the Sub Main() instruction

2a. SYNTAX FOR DECLARING VARIABLES

DIM name1 AS data type


or DIM name1, name2, … AS data type
where name1, name2, etc. are valid variable names

2b. SYNTAX FOR DECLARING CONSTANTS

CONST name1 AS data type = value


where name1 is a valid constant name

2c. OTHER RULES


- If you write an instruction that uses a variable or constant name that has not been declared properly,
the Code Editor will underline it (curly line)
- When a variable is declared as numeric (integer/long/single/double), it is automatically assigned an
initial (or starting) value of 0 (i.e. zero)
- When a variable is declared as a string data type, it is automatically assigned an initial value of
nothing (or null).
- When a variable is declared as a boolean data type, it is automatically assigned an initial value of
false.
- When you declare a constant you must assign the initial value in the declaration. That value can
never be changed in an instruction (because the data item is a constant).

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 6 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
3. RECEIVING DATA FROM A KEYBOARD

3a. SYNTAX

name1 = Console.Readline()
where name1 is the name of a variable which has been declared.
- The data input by the user is automatically assigned to the variable on the left of the equal sign,
e.g.
Instruction: mark1 = Console.Readline()
The user inputs: 54
After the instruction has been executed, the variable called mark1 contains the value 54

3b. RULES
- When the Console.Readline() instruction is executed, the program waits for the user to input data and
press enter (i.e. no other instruction will be executed until the user has pressed enter).
- If the variable used in the instruction is a numeric data type and the user inputs character data, the
program will crash on that instruction.
- When a program ends (i.e. the End Sub instruction is executed), the DOS window being displayed is
automatically closed. Insert a Console.Readline() instruction immediately before the End Sub to keep
the display on the screen until the user presses enter (see examples).

4. DISPLAYING INFORMATION OR DATA ON A SCREEN

4a. SYNTAX FOR DISPLAYING VALUES STORED IN VARIABLES OR CONSTANTS

Console.Writeline(name1)
where name1 is the name of a variable/constant which has been declared.
e.g.
Instruction: Console.Writeline(total)
Displayed on the screen: 57
(if total contains the value 57)

Instruction: Console.Writeline(firstName)
Displayed on the screen: Thabo
(if firstName contains the value Thabo)

4b. SYNTAX FOR DISPLAYING TEXT OR MESSAGES

Console.Writeline(“text”)
where text is the message to be displayed on the screen
Text must be enclosed in double quotes. The double quotes are not displayed or printed.
e.g.
Instruction: Console.Writeline(“Please input your name”)
Displayed on the screen: Please input your name

4c. SYNTAX FOR DISPLAYING MESSAGES AND VALUES TOGETHER

Console.Writeline(“text” & name1)


Separate the text from the variable name with the ampersand symbol: &
e.g.
Instruction: Console.Writeline(“The total price to be paid is ” & total)
Displayed on the screen: The total price to be paid is 57
(if total contains the value 57)
- Note that you must include a space at the end of the message or the value in the variable will
be printed right next to the message (i.e. there will not be a space between them).

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 7 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
4d. SYNTAX FOR INSERTING A BLANK LINE ON THE SCREEN

Console.Writeline()

4e. RULES
- Each Console.Writeline() instruction will move the cursor to a new line on the screen
- Text (enclosed in double quotes) will be displayed EXACTLY as typed in the instruction
- When a program ends (i.e. the End Sub instruction is executed), the DOS window being displayed is
automatically closed. Insert a Console.Readline() instruction immediately before the End Sub to keep
the display on the screen until the user presses enter (see examples).

5. ASSIGNING AND STORING VALUES (excluding receiving data and calculations)

5a. SYNTAX FOR ASSIGNING A LITERAL VALUE TO A NUMERIC DATA ITEM

name1 = value
where name1 is a numeric data item that has been declared
and value is a number
e.g. mark1 = 55.3
the value 55.3 is stored in the variable called mark1

5b. SYNTAX FOR ASSIGNING A LITERAL VALUE TO A CHARACTER DATA ITEM

name1 = “value”
where name1 is a character data item that has been declared
and value can be anything - it must be enclosed in double quotes
e.g. month = “March”
the value March is stored in the variable called month

month = March
will cause the system software to try to assign the current value held in a variable called
March to the variable called month

5c. SYNTAX FOR ASSIGNING A VALUE FROM ANOTHER VARIABLE/CONSTANT TO A DATA


ITEM

name1 = name2
where name1 and name2 are data items of the same data type that have been declared
e.g. highestMark = mark1
topStudent = studentName

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 8 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
6. BASIC CALCULATIONS

Arithmetic operators and order of precedence (from Zak, 2007:157).

Operator Operation Precedence number


^ Exponentiation (raises a number to a power) 1
- Negation 2
*,/ Multiplication and division 3 (left to right)
\ Integer division (gives integer result from a division) 4
Mod Modulus (gives remainder from a division) 5
+,- Addition and subtraction 6 (left to right)

Note that operations within brackets are performed first.

6a. SYNTAX FOR ASSIGNING A RESULT FROM A BASIC CALCULATION TO A VARIABLE

e.g. area = (length ^ 2) + (width ^ 2)

result = num1 \ num2

remainder = num1 MOD num2

7. SELECTION CONTROL STRUCTURES

7a. SYNTAX FOR IF SELECTION *

IF condition THEN
Instructions to be executed if the condition is true
END IF

Or IF condition THEN
Instructions to be executed if the condition is true
ELSE
Instructions to be executed if the condition is false
END IF

Or IF condition1 THEN
Instructions to be executed if condition1 is true
ELSE
IF condition2 THEN
Instructions to be executed if condition1 is false but condition2 is true
ELSE
Instructions to be executed if condition1 is false and condition2 is false
END IF
END IF

* Other variations are possible but not shown here

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 9 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
7b. SYNTAX FOR CASE SELECTION *

Select Case name1


Case value1
Instructions to be executed if value in name1= value1
Case value2
Instructions to be executed if value in name1= value2
Case Else
Instructions to be executed if value in name1<> value1 and <> value2
End Select

Where:
- name1 is a variable that has been declared
- IF data type of variable is character, then values must be enclosed in double quotes.

* Other variations are possible but not shown here

Relational Operators

Operator Operation
= equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
<> not equal to
* All have equal order of precedence and are evaluated from left to right.

Logical Operators (most commonly used)

Operator Operation Precedence Order


NOT reverses the result 1
AND All conditions must be true for the compound condition 2
to be true
OR Only 1 of the conditions has to be true for the 3
compound condition to be true

Order of precedence when arithmetic, relational and logical operators are combined:
1. Brackets
2. Arithmetic (according to arithmetic rules of precedence)
3. Relational (left to right)
4. Logical (according to logical rules of precedence)

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 10 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe
8. ITERATION CONTROL STRUCTURES

8a. SYNTAX FOR THE FOR NEXT LOOP

FOR name1 = start value TO end value [STEP step value]


Instructions to be executed while value in name1 <= end value
NEXT name1

Where:
- name1 is a numeric variable that has been declared
- start value, end value and step value are numeric variables, literals or constants

8b. SYNTAX FOR THE DO WHILE PRE TEST LOOP

DO WHILE condition
Instructions to be executed while the condition is true
LOOP

VISUAL BASIC EXAMPLES

1. Write a Visual Basic program that will ask the user to enter a price and then calculate and display
the VAT amount that must be paid, as well as the total amount (including VAT). (The VAT amount is
14% of the price).

Module Module1
Sub Main()
Dim price, vat, total AS single
Console.Writeline(“Please enter price”)
price=Console.Readline()
vat = price * 0.14
total = price + vat
Console.Writeline("The VAT amount is " & vat)
Console.Writeline("The total amount is " & total)
Console.Readline()
End Sub
End Module

** Note that the last Console.Readline() instruction is used to keep the display on the screen until the
user presses enter.

If the user inputs 100 the following will be displayed on the screen:

Please enter price


100
The VAT amount is 14
The total amount is 114

REFERENCES

Zak, D. (2007). Programming with Microsoft Visual Basic 2005. Third Edition. Boston: Course
Technology, Thomson Learning Inc.

DEVELOPMENT SOFTWARE 1 MODULE 5 Page 11 of 11


Issue 2011/1.0 (FEB 2011)
Author: L v d Merwe

You might also like