Sunteți pe pagina 1din 44

STATSTCS 124: ntroduction to Programming - 1

st
Semester, 2011-2012

1. COMPUTER CONCEPTS

A computer is a collection of devices that function as a unit. t consists basically of hardware,
software, and data.

1.2 Hardware

Hardware is a comprehensive term for all the physical parts of a computer. The whole
point of computer hardware is to make possible three basic operations: nput, Processing and
Storage, and Output. The instruction and information that the computer needs are put into the
computer by way of input hardware. Once the instructions and information are in the computer, it
must have processing and storage hardware to perform its work. After the computer has finished
its work, it must have output hardware. The output hardware delivers data processed by the
computer to the user. These hardware devices that attach to a computer are called peripherals.

Input Hardware

Terminals
A device that is often used for entering instructions and information into the computer is the
terminal. A terminal is a typewriter-like device and comes in many different designs.

Mouse
The mouse may be used instead of a keyboard for inputting data and instructions into the
computer. The user rolls the mouse on a desk top. This moves a pointer of light, called a
cursor, on the computer's screen. The cursor can be pointed at various pictures on the screen,
each of which represents a different job for the computer to do. When the cursor is pointing at
the desired job, the user pushes a button on the mouse and the computer immediately begins to
do that job.

Modem
Another common data input peripheral is the modem. t is a small device that connects to, or is
built into, a computer and has a place to put a telephone handset or to attach a telephone cord.
Over telephone lines, data from one computer can be sent to or received from another
computer having a modem. The data are sent in a series of electrical impulses. These
impulses can be used and processed directly by the computer connected to the modem.

Voice Recognition Device
The voice recognition device accepts data that is spoken rather than typed or recorded on disk
or tape. Voice recognition devices assign numeric values to vocal signals. When the computer
hears a voice pattern (or speech), it compares the numeric values of the speech to numeric
values for other vocal signals stored in its memory. When it finds a pattern that matches the
speech it has heard, it can use the pattern in its memory to understand the signal it has just
received. Then it carries out the instructions it has been given.

Optical Character Recognition
Just as the computer can "hear" voice patterns, it can also "see" written or printed characters. t
does this be using optical character recognition, or OCR. OCR devices work like the human
eye to "see" characters and marks. OCR devices have many uses. One of the most common
is the bar code reader used in stores.


STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


!rocessing and Storage Hardware

CPU
The CPU in a microcomputer is called a microprocessor and it has two different sections. The
control unit controls the other parts of the computer system and regulates the work they do.
The arithmetic logic unit, or ALU, performs all of the computing operations of the computer.

RAM and ROM
ROM stands for read-only-memory. This means that the computer can only read information
from the ROM chip. The manufacturer of the ROM chip puts information onto the chip. This
information is usually a program that tells the computer how to perform a specific job.
RAM stands random-access memory. The user puts programs into the RAM chip. nstructions
and information stored on a RAM chip can be erased and rewritten whenever the user needs to
store different information.

Secondary Storage
Two popular types of secondary storage are magnetic tape and magnetic disks. Tape and
disks record data in spots on their surface that are electrically charged. The computer reads
these charges like a code that stands for the data that has been stored.

Output Hardware

CRT or Screens.
Terminals displays information on a TV like device called a CRT, screen, or monitor. The
computer usually processes the information much faster than a human can follow on a
terminal. But the terminal is a very convenient way for a person to immediately see the output.

Printers.
Probably one of the most common types of devices used to output information is the printer.

Speakers/Headphones
Computers produce audio data that require output devices such as speakers and headphones
to deliver the sound to the user. Audio data is created by the computer and then sent to the
audio card, which is located in an expansion slot. The card translates the data into audio
signals, which are sent to the audio output device.

CD/DVD/Floppy Disc
CD, DVD and floppy disc are output devices that can also be used as storage and input
devices. The computer sends data to the disc, where it is embedded and can be later retrieved.

Projector
Projectors are display devices that project a computer created image. The computer sends the
image data to the video card which then sends the video image to the projector. They are
typically used for presentations or for viewing videos.


1.3 Software

Computer software is a general term used to describe a collection of computer programs,
procedures and documentation that perform some tasks on a computer system.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


%pes of Computer Software

$stem software helps run the computer hardware and computer system. The purpose of
systems software is to insulate the applications programmer as much as possible from the
details of the particular computer complex being used, especially memory and other hardware
features, and such as accessory devices as communications, printers, readers, displays,
keyboards, etc.

Programming software usually provides tools to assist a programmer in writing computer
programs, and software using different programming languages in a more convenient way. The
tools include text editors, compilers, interpreters, linkers, debuggers, and so on. An ntegrated
development environment (DE) merges those tools into a software bundle, and a programmer
may not need to type multiple commands for compiling, interpreting, debugging, tracing, and
etc., because the DE usually has an advanced graphical user interface, or GU.

Application software allows end users to accomplish one or more specific (non-computer
related) tasks. Typical applications include industrial automation, business software, educational
software, medical software, databases, and computer games.

1.4 Programming Languages

The most complex and integrate computer hardware is useless without instructions
telling it what to do. These instructions are called programs and are written in computer
programming languages. A programming language is a set of written words and symbols that
allow the programmer or user to communicate with the computer.

4 Categories of Programming Languages

A. Machine Language

Machine Language is the fundamental language of the computer's processor. Programs
written on any other category of languages are converted into machine language before they
are executed. Machine Languages are unique to particular processors.

B. Assembly Language

An assembly language is similar to a machine language but uses abbreviations called
mnemonics or symbolic operation code to represent the machine operation code. Assembly
languages are converted into machine language instructions by a special program called an
assembler.

C. High-Level Languages

High-level languages more closely resemble what most people would think of as a
language in that they contain nouns, verbs, and mathematical, relational, and logical
operators that can be grouped together to form what appear to be sentences called program
statements. High-level languages are easier to learn than machine or assembly languages.
Furthermore, they are machine-independent and can run on different types of computers.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

A computer does not understand high level language. Several translations must be
accomplished before it will understand what the programmer intended. The instructions in a
high-level language must be translated into the one language a computer understands -
machine language. There are two types of programs that perform the task of translating high-
level languages into machine language- interpreters and compilers
IN%#!#%#S COM!IL#S
An interpreter translates the high-level
instructions into machine code, line-by-line
as the program is running. The source
code must be translated every time the
program is run.
A compiler converts an entire program into
machine language that is usually stored for
later execution. The program to e converted
is called the source code and the machine
language produced is called the object
code.
nterpreted programs do not run as fast as
compiled programs.
Compilers produce an error listing of all
program statements that do not meet the
program language rules.
D. Fourth-Generation Languages

Fourth-generation Languages (4GL's) are advanced computer programming languages
that are more like human language than are the standard high-level programming languages.
They are non-procedural, which means that the programmer does not specify the procedures
that need to be used to accomplish a certain task. nstead of telling the computer how to do
the task, the programmer tells the computer what is to be done, usually by describing the
desired output.

CommonIy used programming Languages Today

High-level Language

O BASC Beginner's All-purpose nstruction Code
This language was developed by John Kemeny and Thomas Kurtz in 1964 at Dartmouth
College.
O COBOL Common Business Oriented Language
ntroduced in 1960, it is one of the most widely used programming language for
business applications.
O C
C was developed in 1972 by Dennis Ritchie. Originally designed as a programming
language for writing systems software, it is now considered a general-purpose
programming language.
O FORTRAN Formula Translator
Released in 1957, it is considered the first high-level language that was developed and
is noted for its capability to easily express and efficiently calculate mathematical
equations.
O PASCAL
t was named after Blaise Pascal, the mathematician who developed one of the earliest
calculating machines. t was developed in 1968 by Niklaus Wirth and was developed for
teaching programming.
O ALGOL Algorithmic Language
Structured programming Language used for scientific and mathematical applications.
O JAVA
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Java is a programming language originally developed by Sun Microsystems and
released in 1995 as a core component of Sun Microsystems' Java platform.

ourth-Generation Language

O General Use / Versatile

DataFlex; Fort TOOL (transactional object-oriented language); BM
VisualAgen/VisualAge Generator; PowerBuilder; SheerPower4GL (Microsoft Windows
Only); SQLWindows/Team Developer; WinDev; Up ! 5GL; Visual DataFlex (Microsoft
Windows Only); Discovery Machine Modeler.
O Database Query Languages
FOCUS; Genero; SB+/SystemBuilder ; nformix-4GL; NATURAL ; Progress 4GL;
SQL
O Report generators
BuildProfessional; GEMBase; DL-PV/WAVE; LNC; Metafont; NATURAL;
Oracle Reports; PostScript; Progress 4GL Query/Results; Quest; Report Builder;
RPG-
O Data manipulation, analysis, and reporting languages
Ab nitio; ABAP; Aubit-4GL; Audit Command Language; Clarion Programming
Language; CorVision; Culprit; ADS/Online (plus transaction processing); DASL;
FOCUS; GraphTalk; DL; GOR Pro; nformix-4GL; LANSA; LabVEW; MAPPER
(Unisys/Sperry) now part of BS; MARK-V (Sterling/nformatics) now VSON:
BULDER of CA; Mathematica; MATLAB; NATURAL; Nomad; PL/SQL; Progress
4GL; PROV; R; Ramis; S; SAS; SPSS; Stata; Synon; XBase++
O Data-stream languages
APE; AVS; ris Explorer
O Database driven GU Application Development
Genexus; SB+/SystemBuilder; Progress Dynamics; UNFACE
O Screen painters and generators
FOURGEN CASE Tools for Rapid Application Development by Gillani;
SB+/SystemBuilder; Oracle Forms; Progress 4GL ProVision; Unify Accell
O GU creators
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

4th Dimension (Software); eDeveloper; MATLAB's GUDE; Omnis Studio;
OpenROAD; Progress 4GL AppBuilder; Revolution programming language;
Sculptor 4GL
O Web development languages
ColdFusion; CSS





2. FUNDAMENTALS

2.1 Basic concepts and Definitions

An algorithm is a step-by-step list of instructions for solving a particular problem.

The term variable, in computer terminology, means (1) storage location in the memory of a
computer reserved for a specific data item; or (2) the data item itself that is stored in the
corresponding storage location.

Variable name is a name given to a variable. Normally, one chooses names that indicate the
kind of data item they represent.

#eserved words have a special meaning in programming language and hence cannot be
chosen as variable names. (Examples are Data, Stop, f and Let)

A constant is an item of data that does not change during the execution of a program. A
numeric constant is a signed or unsigned number, with or without a decimal point that
contains neither commas nor blank spaces. A nonnumeric constant is simply a string of
characters from the character set of the language. One indicates a nonnumeric constant by
placing its name between single quotation marks.











STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

2.2 FIowcharting

A flowchart is a visual representation of an algorithm. t is a diagram consisting of
symbols (polygons) and arrows (flowlines) that connect one symbol to another. t is usually
drawn so that the flow direction is downward or from left to right.

2.2.1 SymboIs used

Name SymboI Purpose
Terminal

- ndicates the beginning or end of an algorithm
- A flowchart can contain only one Start
symbol; however, it can contain more than one
stop symbol.
nput/Output
- When used with the "Read statement, it
indicates that data are to be inputted into the
specified locations.
- When used with the word "Write it indicates
that data are to be outputted from the specified
locations.
Process

- Used to indicate a processing operation. This
can be in the form of an assignment statement
or a macroinstruction, whose programming
language translation would require an entire list
of computer statements.
Decision

- Used to indicate a decision, wherein a
computer can be programmed to take a
different course of action depending upon the
answer to a certain question.
- The computer can determine the truth value
of a statement involving one of the following
mathematical relations: equal to ( = ); not equal
to ( = ); less than ( < ); less than or equal ( > );
greater than ( > ); or greater than or equal ( < )
- The computer can also be programmed to
answer questions which involve one or more of
the logical connectives "and, "or and "not.
- Depending upon the answer, an exit arrow
which points to the appropriate next step of the
algorithm must be labeled. The decision
symbol is the only symbol that may have more
than one exit.
Connector

- n cases when the flowchart is long and
complex or confusing due to crossing flowlines,
a connector symbol is used. Letters of the
alphabet are used to "connect a step to
another step in the next page of the flowchart
or to a step on distant part of the same page.
Preparation

- This indicates the preparation for some
symbol by initializing certain variables.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


dvantages of using flowcharts

A. Flowcharts are better way of communicating the logic of a system to all
concerned.
B. With the help of flowchart, problem can be analyzed in more effective way.
C. Program flowcharts serve as a good program documentation, which is needed
for various purposes.
D. The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
E. The flowchart helps in debugging process.
F. The maintenance of operating program becomes easy with the help of flowchart.
t helps the programmer to put efforts more efficiently on that part.

Limitations of using flowcharts

A. Sometimes, the program logic is quite complicated. n that case, flowchart
becomes complex and clumsy.
B. f alterations are required the flowchart may require re-drawing completely.


2.2.2 Looping

Looping is the process of repeating a procedure for every record in a file. The
handling of each record constitutes one cycle or iteration. Normally, a data processing
system uses a record with special data at the end of each file. This is called the end-of-
file (EOF) record. Accordingly, after a record has been read, the computer may be asked
whether the EOF record has been reached.

2.2.3 InitiaIization using Counters and AccumuIators

A counter is a numeric variable, usually incremented by 1, used for counting. t
is commonly used to count the number of records that has been processed in a
procedure. The counter variable must be assigned an initial value in preparation for the
loop, and the final value is output upon leaving the loop.

An accumulator is a numeric variable used to find the sum of another variable
after every record is read. Like the counter, the accumulator must be initialized in
preparation for the loop.

A DO loop is used when a certain procedure is to be executed exactly N times,
where N is a positive integer. The loop involves a counter labeled K, which increases by
1 after every iteration. f K exceeds the value limit N, we exit the loop; otherwise, the
procedure is repeated. The variable K is called the index of the DO loop, and the
procedure which is iterated is called the body of the loop.






STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

2.3 Pseudocodes

A pseudocode is a description of a computer programming algorithm that uses the
structural conventions of programming languages, but omits detailed subroutines or language-
specific syntax (wikipedia). Pseudocode is not a rigorous notation, since it is read by other
people, not by the computer.

dvantages
Following are some of the advantages of using pseudocode:
1. Converting a pseudocode to a programming langauge is much easier than converting a
flowchart.
2. As compared to flowchart, it is easier to modify a pseudocode of a program logic when
program modifications are necessary.

Limitations
t also suffers from some of the limitations. These limitations are as follows:
1. n the cases of pseudocode, a graphic representation of program logic is not available.
2. There are no standard rules to follow for using a psudocode. Different programmers use
their own style of writing pseudocode and hence, communication problem occurs due to
lack of standardization.



!seudocode !rogram Organization

1. Sequence logic involves executing instructions one statement after another-in the order
presented by the program. This is the simplest and most-used pattern. The computer
assumes that all instructions are to be executed in this order unless the program presents
other instructions. The instructions are executed in order, from top to bottom.

2. Selection logic requires that the computer make a choice among two or more items. t
employs F-structures, each of which is essentially a selection of one out of several
alternatives.

O F-THEN Structure the simplest structure in selection logic. f the condition is true, then
the process is executed and if the condition is not true, the process is skipped and
subsequent process (if any) is executed. ENDF is used to indicate the end of the
structure.
F condition THEN
Process
ENDF

O F-THEN-ELSE Structure indicates that if the condition is true, then process 1 is
initiated, if the condition is not true (else), then process 2 is executed.
F condition THEN
Process1
ELSE
Process2
ENDF
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


O Case Structure used when there are three or more alternative to one decision.
F condition1 THEN
Process1
ELSEF condition2 THEN
Process2
.
.
ELSEF conditionN THEN
ProcessN
ELSE
ProcessN1
ENDF

3. teration Logic contains a Loop Pattern which causes an interruption in the normal
sequence of processing and directs that computer to loop back to a previous statement in
the program, repeating the same sequence over again, usually with new data. By looping,
the programmer avoids having to repeat the same set of instructions over and over.



O FOR-NEXT Structure also called an automatic counter loop, it executes a block of
instructions a specified number of times.

FOR = startV to endV (by j)
(ncrement by j)
Loop instructions
NEXT k

O DOWHLE Structure as long as the condition is true, the block of instructions inside the
loop is executed.

DOWHLE condition
Loop instructions
Increase counter
ENDDO

There must be a statement before the loop that initializes the condition which
controls the loop, and there must be a statement in the body of the loop that changes
the condition, in order that looping may eventually cease.

O DOUNTL STRUCTURE repeatedly executes a block of instructions until a condition
becomes true.

DOUNTL condition
Loop instructions
Increase counter
ENDDO


STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Several keywords are often used to indicate common input, output, and processing operations.
nput: NPUT, READ, OBTAN, GET
Output: PRNT, DSPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMNE
nitialize: SET, NT
Add one: NCREMENT, BUMP


%ips for Writing !seudocodes

1. Before starting, determine whether the problem requires selection or iteration logic and
where they are needed. Use control structures and their corresponding keywords to
describe how the solution is organized
2. Conventional mathematical / logical symbols are allowed, but language-specific syntax is
not.
3. Variables requiring initialization, such as summations and counters, must be properly
initialized.
4. Use indentation and blank lines to improve readability.
5. Pseudocodes should be self-explanatory. t would be best if there are no comments
within the pseudocode. f absolutely necessary (such as when variable type need to be
explained), comments should be kept to a minimum.
6. Remember, the purpose of pseudocode is to help make the programming easier.
Therefore, you must honestly attempt to add enough detail to your pseudocode. Ask
yourself, "Could someone else easily write the program using my pseudocode?"


3. VISUAL BASIC (VB) 6.0

3.1 Introduction to VB

The Visual Basic (VB) system is a fourth generation programming system which
produces much of the code itself as the programmer designs the interface for his or her
application. Prior to Visual Basic, Windows applications programming required mastery of huge
subroutine libraries and hundred of lines of code to create even simple screen elements. VB
eliminates the need to write code for GU input/output, thus reducing by orders of magnitude the
length of code and time to develop an application.

The following are the original design principles of Visual Basic

O t is as safe a language to write in as possible. n general, Visual Basic tries to balance
reliability, ease of use, and efficiency in the definition of the language.
O t is an extremely approachable language.
O t enables rapid program development, while not compromising reliability.
O t produces predictable and efficient code.
O t works as a strongly typed language, as well as a loosely typed one, for more correct user
code in the former case, and for faster development in the latter.




STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

3.1.1 History

Visual Basic evolved from BASC (Beginner's All-purpose Symbolic nstruction Code),
which was developed in the mid-1960's by Professors John Kemeny and Thomas Kurtz of
Dartmouth College.

Visual Basic 1.0 for Windows was first released on May 20, 1991. t combined the ease of
graphical design with the power and versatility of traditional programming. Developers
simply drew the user interface and attached code that responded to events.
VB version 2.0 for Windows (November 1992) was faster, more powerful and easier to
use than version 1. VB 2 was also available in a freeware student release called the
Primer edition.
Visual Basic 3.0 (1993) added tools to access and control databases and Object Linking
and Embedding (OLE) version 2. t came in Standard and Professional versions.
Visual Basic 4 was released in 1995 and supported the new Windows 95 family of 32-bit
operating systems.
With the introduction of Visual Basic version 5 in early 1997, 16-bit systems were no
longer supported. Between versions 4 and 5, significant changes were made in the user
interface. Visual Basic 5 added, among other things, the ability to create true executables
and to create your own custom controls. t also supported Microsoft's Active-X technology.
Visual Basic 6 (VB6) was introduced in 1998 and was included as part of a package known
as Visual Studio 6.0 that also included Microsoft's Visual C++ development system. VB6
added new capabilities in the areas of data access, nternet features, controls, component
creation, language features and wizards. Many organizations are still using this version
today.


3.1.2 The VB integrated deveIopment environment (IDE)

The VB6 DE (ntegrated Development Environment) is a very simple and fully featured
DE. t allows the programmer to run and debug Windows programs in one application
without the need to open additional programs (i.e. one program to create, separate
program to debug, and yet another one to execute).

Creating A Project

1. Start VB6
2. When presented with a "New Project" dialog you will usually want to pick "Standard
EXE" and press "OK"
3. You now see the VB6 DE, which contains an empty form called "Form1". That is your
program.

Project-Form Window

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

The window named Project-Form 1 contains a window named Form1 (default form),
which is where the program's Graphical User nterface (GU) will be displayed. A GU is the
visual portion of the program this is where the user enters data and where the program
outputs results for the user to read.

Project Window

The window title Project-Project 1 is called the Project Explorer and contains the project
files. t groups the project's files by type and contains the following buttons:

O View Code displays a window for writing VB code
O View Object displays the form
O Toggle Folders alternately hides or shows the Forms folder.


%oolbox

The toolbox contains prepackaged components called Controls that can be used to
customize forms.

TabIe 3.1 - TooIbox controI summary

ControI Function
PictureBox Displays mages
Label Displays uneditable text to the user
TextBox Displays a box where the user can input information. t
can also display editable text
Frame Used for grouping a set of Controls
Command Button Displays a button that the user clicks to initiate an action
CheckBox Provides the user with a set of options (multiple
responses accepted)
OptionButton Provides the user with a set of options (only one
response can be selected)
ListBox Provides a list of items
ComboBox Provides a short list of items
HscrollBar Horizontal scroll bar
VscrollBar Vertical scroll bar
Timer Performs a task at programmer-specified intervals. t is
not visible to the user.
DriveListBox Used for accessing the system disk drives
DirListBox Used for accessing directories in a system
FileListBox Used for accessing files in a directory
Shape For drawing circles, rectangles, squares, or ellipses
Line For drawing lines
Data Used for connecting to a database
OLE Used for interacting with other window applications




STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Form Laout Window

The form layout window specifies a form's position on the screen at runtime. This is
done by clicking the mouse pointer over the form image and dragging it to the preferred
location.

Properties Window

The properties window displays the properties for a form or control. t lets you change
the characteristics, or property setting, of the user interface elements on the form. t
contains an object drop-down list box that itemizes all the user interface elements (objects)
on the form.

Some properties, like width and height, are common to both forms and controls, while
other properties are unique to a form or control. Controls often differ in the number and type
of properties.

Menu Bar and %ool Bar

Commands for developing, maintaining, and executing programs are contained in the
following menus: File, Edit, View, Project, Format, Debug, Run, Query, Diagram, Tools,
Add-ins, Windows, Help.

The tool bar is comprised of pictures called icons that represent commands.



3.2 Working with simpIe projects

3.2.1 Concepts and TerminoIogies

Generally, there are three basic steps in building a VB application.
Step 1: Design the interface
Step 2: Set Properties of the controls (Objects)
Step 3: Write the events' procedures

asic Concepts

CONTROL
A control is a tool that is used to draw/create an object on the Form to enable or enhance
user interaction with an application.

OBJECT
Objects are user interface elements that are drawn on the form. Objects have properties
that define aspects their appearance, such as position, size and color, and aspects of their
behavior, such as their response to the user input. They can respond to events initiated by
the user or set off by the system.

PROPERTY
Before writing an event procedure for the object to respond to a user's input, you have to
set certain properties for the object to determine its appearance and how it will work with
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

the event procedure. You can set the properties of the objects in the properties window or
at runtime.

n code, the format for setting a property is Object.Property = Value

EVENT PROCEDURE
An event procedure is a block of code that is executed when an object is manipulated in the
program. To start writing an event procedure, you need to double-click an object. For
example, if you want to write an event procedure when a user clicks a command button,
you double-click on the command button and an event procedure will appear, taking the
following format:

Private $ub Command1_Clic

End $ub

PROGRAM STATEMENT
A program statement is any combination of Visual Basic keywords, properties, functions,
operators, and symbols that collectively create a valid instruction recognized by the Visual
Basic compiler. A complete program statement can be a simple keyword such as beep, or
a combination of elements.

VARABLE
Variables are the memory locations which are used to store values temporarily. The
programmer creates variables to store the results of a calculation, create filenames,
process input, and so on. Numbers, names, and property values can be stored in variables.

METHOD
A special statement that performs an action or a service for a particular object in a program.

SYNTAX
The rules of construction that must be used when you build a programming statement are
called statement syntax. The trick to writing good program statements is learning the syntax
of the most useful language elements and then using those elements correctly to process
the data in your program.


3.2.2 Forms and Object Programming

orms

A typical application has more than a single Form. When an application runs the main Form
is loaded. By setting the Project properties you can control which Form is to be displayed in
the Start-Up of the application.

n order to load and unload the forms, Load and Unload statements are used. The Load
statement has the following syntax:

Load FormName

And the Unload statement has the following syntax:
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


Unload FormName

Show method is used to Show a Form. f the Form is loaded but invisible, the Show method
is used to bring the Form on Top every other window. f the Form is not loaded, the Show
method loads it and then displays it.

Syntax of the Show method of the Form:

FormName.Show

Hiding Forms

The Hide method is used to hide a Form. The following is the syntax of the Hide Method.

FormName.Hide

To hide a Form from within its own code, the following code can be used.

Me.Hide

Forms that are hidden are not unloaded; they remain in the memory and can be displayed
instantly with the Show Method. When a Form is hidden, you can still access its properties
and code. For instance, you can change the settings of its Control Properties or call any
Public functions in the Form.

Object !rogramming

Objects are combinations of code and data that can be treated as single units. Nearly
everything you do in Visual Basic involves objects, from the controls you use to the forms
on which you place them.When you create an application in Visual Basic, you constantly
work with objects. You can use objects provided by Visual Basic, such as controls, forms,
and data access objects. You can also use objects from other applications within your
Visual Basic application. You can even create your own objects and define additional
properties and methods for them. Objects act like prefabricated building blocks for
programs they let you write a piece of code once and reuse it over and over.


3.2.3 VariabIes and Operators

Variable Names

The following are the rules when naming the variables in Visual Basic

O May be as much as 255 characters long
O Must not contain a space or an embedded period or type-declaration characters
used to specify a data type; these are ! # % $ & @
O A name must begin with a letter, never a number
O Must not be a reserved word (that is part of the code, like Option, for example)
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

O The dash, although legal, should be avoided because it may be confused with the
minus sign. nstead of First-name use First_name or FirstName.

plicit Declaration of Variables

n Visual Basic, one needs to declare the variables before using them by assigning names
and data types. They are normally declared in the general section of the codes' windows
using the Dim statement. The format is as follows:

Dim variableName as DataType







Numeric Data Types
%pe Storage #ange of Values
Byte 1 byte 0 to 255
nteger 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.
Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for
negative values
4.94065645841247E-324 to 1.79769313486232e+308 for
positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is
used. +/- 7.9228162514264337593543950335 (28 decimal
places).

Nonnumeric Data Types
%pe Storage #ange of Values
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string

f data type is not specified, VB will automatically declare the variable as a Variant.

ssigning Values to Variables
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

After declaring various variables using the Dim statements, we can assign values to those
variables. The general format of an assignment is
Variable = Expression
The variable can be a declared variable or a control property value. The expression could
be a mathematical expression, a number, a string, a Boolean value (true or false) and etc.
The following are some examples:
firstNumber = 100
secondNumber = firstNumber-99
username = "John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
Note: You can assign a value to a variable without first explicitly declaring the variable. This
is called implicit declaration. mplicit declaration has a speed advantage because you don't
spend time typing the dim statement, but it is discouraged because it prevent visual basic
from displaying an error message if you mistype the variable name later on.
f you decide to always declare your variables using the Dim statement, you might want
to put the 'Option Explicit' statement in the declarations section of your startup form. You
can do this automatically for each new project by clicking the Options command on the
tools menu, clicking the editor tab, and adding a check mark to the Require Variable
Declaration textbox.

3.2.4 Functions

A function is similar to a normal procedure but the main purpose of the function is to accept
a certain input and return a value which is passed on to the main program to finish the
execution. There are two types of functions, the built-in functions (or internal functions) and
the functions created by the programmers.

The general format of a function is

FunctionName (arguments)

The arguments are values that are passed on to the function.

Mathematical Functions - are very useful and important in programming because very often
we need to deal with mathematical concepts in programming such as chance and
probability, variables, mathematical logics, calculations, coordinates, time intervals and etc.

Formatting Functions - formatting output is a very important part of programming so that the
data can be presented systematically and clearly to the users. To have better control of the
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

output format, we can use a number of formatting functions in Visual basic such as Tab,
Space and Format.

$tring Manipulation Functions - the string variable is the most used variable in user
interface programming. You grab data in strings, you display information to users through
strings, and along the way you use strings continuously. Visual Basic provides string
manipulation functions to enable the programmer to manipulate these strings.

3.2.5 Working with Specific Data Types

A variable is scoped to a procedure-level (local) or module-level variable depending on how
it is declared. The scope of a variable, procedure or object determines which part/s of the
code in our application is/are aware of the variable's existence. A variable is declared in
general declaration section of e Form, and hence is available to all the procedures. Local
variables are recognized only in the procedure in which they are declared. They can be
declared with Dim and Static keywords.

Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to
the code inside the procedure and can be declared using the Dim statements as given
below.
e.g.: Dim sum As nteger

$tatic Variables
Static variables are not reinitialized each time Visual Basic invokes a procedure and
therefore retains or preserves value even when a procedure ends. A static variable is
declared as given below.
e.g.: Static tot As nteger

Module level Variables
A module level variable is available to all the procedures in the module. They are declared
using the Public or the Private keyword.
e.g.: Public ans As nteger
Private Temp As nteger


3.2.6 Constants

A constant is a meaningful name that takes the place of a fixed number or text string.
Constants are different from variables in the sense that their values do not change during
the running of the program. They are useful because they increase the readability of
program code, using them can save memory and they make global changes easier to
accomplish later.

Declaring a Constant

The format to declare a constant is

Const Constant Name As Data Type = Value

Examples
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


Const Pi As Single = 3.14159265
Const Temp As Single = 37000
Const Note As String = "My name is

Public Const Pi = 3.14159265


3.3 Programming with VB

3.3.1 VisuaI Basic Operators

rithmetic Operators

n the absence of parentheses, ( ), Visual basic evaluates arithmetic operators according
to the following strength (strongest to weakest)

Operator Description ExampIe ResuIt
) Exponentiation 3 ) 3 27
- Negation - 5 - 5
* Multiplication 5 * 4 20
/ Division 25 / 5 5
\ nteger Division 20 \ 3 6
Mod Remainder of Division 20 Mod 6 2
+ Addition 5 + 5 10
- Subtraction 10 5 5
& String Concatenation "Stat & " " & "124 Stat 124

Examples:

6 6 + 9 / 3 ) 2 =
8 Mod 4 * 3 / 2 + 10 =

Notes:
f the parentheses are nested then the expression in the innermost pair is evaluated
first.
f there are several same operators in one expression, they are evaluated from left to
right.

#elational Operators

Operator Description ExampIe ResuIt
> Greater than 10 > 8 True
< Less than 10 < 8 False
>= Greater than or equal to 20 >= 10 True
<= Less than or equal to 10 <= 20 True
<> Not equal to 5 <> 4 True
= Equal to 5 = 7 False
Logical Operators
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Operator Description ExampIe ResuIt
OR
Operation will be true if
either of the operands is
true
10 > 8 OR 10 < 9 True
AND
Operation will be true only if
both the operands are true
10 < 8 and 10 > 9 False
NOT
Operation will be true if the
operand is false
Not 5 = 7 True




3.3.2 VisuaI Basic Functions

Msgo ) unction

The objective of MsgBox is to produce a pop-up message box and prompt the user to
click on a command button before he /she can continue. This format is as follows:

yourMsg = MsgBox (Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Title
argument will display the title of the message board. The Style Value will determine
what type of command buttons appear on the message box.

$tle Values

Style Value Name Buttons Displayed
0 vbOkOnly Ok
1 vbOkCancel Ok, Cancel
2 vbAbortRetrygnore Abort, Retry, gnore
3 vbYesNoCancel Yes, No, Cancel
4 vbYesNo Yes, No
5 vbRetryCancel Retry, Cancel

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function.
The values are determined by the type of buttons being clicked by the users. t has to
be declared as nteger data type in the procedure or in the general declaration section.

Return Values and Command Buttons

Style Value Name
1 vbOk
2 vbCancel
3 vbAbort
4 vbRetry
5 vbgnore
6 vbYes
7 vbNo

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


To make the message box looks more sophisticated, you can add an icon besides the
message. There are four types of icons available in VB

VaIue Named Constant Icon
16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbnformation


Inputo ) unction

An nputBox( ) function will display a message box where the user can enter a
value or a message in the form of text. The format is

myMessage=nputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type but typically it is declared as a string, which accepts
the message input by the users. The arguments are as follows:
O Prompt - The message displayed normally as a question asked.
O Title - The title of the nput Box.
O default-text - The default text that appears in the input field which users can type
the intended input or change to the message they wish to key in.
O x-position and y-position - the position or the coordinate of the input box.

Mathematical functions

As with other functions, Mathematical functions must be used in a program
statement, and they will return a value to the program.

Function Purpose
Abs(n) Returns the absolute value of n
Atn(n) Returns the arctangent of n (in radians)
Cos(n) Returns the cosine of the angle n
Exp(n) Returns the constant e raised to the power n
nt(n) Returns the largest integer less than n
Fix(n)
For n greater than 0, same as int. For n less than 0, returns the
smallest integer greater than n
Log(n) Returns the natural logarithm of n
Rnd(n) Generates a random number between 0 and 1
Round(n,m) Rounds the number n to m decimal places
Sgn(n) Return -1 if n is less than zero, o if n = 0, and +1 if n is greater than 0
Sin(n) Returns the sine if the angle n
Sqr(n) Returns the square root of n
Str(n) Converts a numeric value to a string
Tan(n) Returns the tangent of the angle n

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


String Manipulation unctions

Function and Syntax Purpose
Len( ) Returns a Long containing the length of the specified
string
Mid$(string, start, [length]) Returns a substring containing a specified number of
characters from a string.
Left$(string, length) Returns a substring containing a specified number of
characters from the beginning (left side) of a string.
Right$(string, length) Returns a substring containing a specified number of
characters from the end (right side) of a string.
UCase$(string) Converts all lowercase letters in a string to uppercase.
Any existing uppercase letters and non-alpha characters
remain unchanged.
LCase$(string)
Converts all uppercase letters in a string to lowercase.
Any existing lowercase letters and non-alpha characters
remain unchanged.
nStr([start,] string1,
string2, [compare])
Returns a Long specifying the position of one string
within another. The search starts either at the first
character position or at the position specified by the
start argument, and proceeds forward toward the end of
the string (stopping when either string2 is found or when
the end of the string1 is reached).
String$(number, character)
Returns a string containing a repeating character string
of the length specified.
Space$(number)
Returns a string containing the specified number of
blank spaces.
Replace$(expression, find,
replacewith[, start[, count[,
compare]]])
Returns a string in which a specified substring has been
replaced with another substring a specified number of
times.
StrReverse$(string)
Returns a string in which the character order of a
specified string is reversed.
LTrim$(string) Removes leading blank spaces from a string.
RTrim$(string) Removes trailing blank spaces from a string.
Trim$(string)
Removes both leading and trailing blank spaces from a
string.



3.3.3 Converting Data types in VB

Function Purpose
CBool Takes any valid expression and converts it to Boolean. Values of
zero convert to False, all others to True. f the expression is String, it
must be a string that can be converted to a number (like "123"). The
strings "True" and "False" will also work; any other string will result in
an error.
CByte Converts an expression to a Byte data type. The value of the
expression is rounded up, must not exceed 255, and must not be
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

negative.
CCur Converts an expression to a Currency data type. The expression
must be a number (or a string representation of a number) that is
with the Currency range. The result is rounded off at the 4th digit
after the decimal point.
CDate Converts a numeric or string expression to a Date data type. (For
numeric expressions, 0 represents the date 12/30/1899. Negative
values represent dates before 12/30/1899; positive values represent
dates after. The decimal portion of a number represents the time (for
example, .5 = noon.) Numeric or string arguments outside of the
range of the Date data type (1/1/100 thru 12/31/9999) results in an
error.
CDbl Converts an expression to a Double data type. The expression must
be a number (or a string representation of a number) that is within
the Double range.
Cnt
Converts an expression to an nteger data type. The expression
must be a number (or a string representation of a number) that is
within the nteger range. Values with digits after the decimal point
are automatically rounded to the nearest integer
CLng Converts an expression to a Long data type. The expression must
be a number (or a string representation of a number) that is within
the Long range. Values with digits after the decimal point are
automatically rounded to the nearest integer.
CSng Converts an expression to a Single data type. The expression must
be a number (or a string representation of a number) that is within
the Single range.
CStr Converts a variable of any datatype to a string. f the argument is a
Date, the "short format" date (m/d/yy) is returned. f the argument is
Boolean, the string "True" or "False" is returned. f the argument is a
number, a string representation of the number is returned.
CVar Converts a variable to a Variant. f the argument is numeric, the
result is a Double; for non-numeric values, the result is a String.
Val The Val function is a more generic (and less efficient) way to convert
a string to a number. Technically, it returns a Double data type. t
strips all blanks from a string argument and then converts the
remaining characters to a number. The Val function recognizes a
leading sign, digits, and a decimal point as part of a number; it will
stop scanning the string at the first character that cannot be
considered part of a number. f the string cannot be converted to a
number, 0 will be returned.
Str$ The Str function is an older function (dating back to earlier versions
of BASC) that converts a number to a string. When numbers are
converted to strings, a leading space is always reserved for the sign
of number. f number is positive, the returned string contains a
leading space and the plus sign is implied. The Str function
recognizes only the period (.) as a valid decimal separator.




STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


3.4 ControI Structures

3.4.1 Introduction

Control structures allow you to control the flow of your program's execution. f left
unchecked by control-flow statements, a program's logic will flow through statements
from left to right, and top to bottom. While some very simple programs can be written with
only this unidirectional flow, and while some flow can be controlled by using operators to
regulate precedence of operations, most of the power and utility of any programming
language comes from its ability to change statement order with structures and loops.

3.4.2 SequentiaI Structure

Sequential structure involves statements in a program that are executed one
after the other, in the order in which they are written.

3.4.3 SeIection Structure

If / then selection structure
The f / Then selection structure performs an indicated action only when the
condition is true; otherwise the action is skipped.

f <condition> Then
statement
End f

e.g.: f average>75 Then
txtGrade.Text = "A"
End f
If / %hen / lse selection structure
The f / Then / Else selection structure allows the programmer to specify that a
different action is to be performed when the condition is True than when the condition is
False.

f <condition > Then
statements
Else
statements
End f

e.g.: f average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End f













STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


Multiple If / %hen / lse selection structure

Multiple f / Then / Else selection structures test for multiple cases by placing f /
Then / Else selection structures inside f / Then / Else structures.

Method 1
f < condition 1 > Then
statements
Elsef < condition 2 >
Then
statements
Elsef < condition 3 >
Then
statements
Else
Statements
End f





Method 2
f < condition 1 > Then
statements
Else
f < condition 2 > Then
statements
Else
f < condition 3 > Then
statements
Else
Statements
End f
End f
Endf



e.g.:
f average > 75 Then
txtGrade.Text = "A"
Elsef average > 65 Then
txtGrade.Text = "B"
Elsef average > 55 Then
txtGrade.text = "C"
Elsef average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End f
Select Case selection structure
Select Case structure is an alternative to f / Then / Elsef for selectively
executing a single block of statements from among multiple block of statements. t is
more convenient to use than the f / Else / End f.

Select Case ndex
Case 0
Statements
Case 1
Statements
End Select

e.g.:
average = txtAverage.Text

Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case Else
MsgBox "nvalid
average marks"
End Select

3.4.4 Repetition Structure
A repetition structure allows the programmer to communicate to the program that an
action is to be repeated until given condition is satisfied.

Do While / Loop Statement
The Do While / Loop is used to execute statements until a certain condition is
met. A variable number is initialized and then the Do While Loop starts. First, the
condition is tested; if condition is True, then the statements are executed. When it gets
to the Loop it goes back to the Do and tests condition again. f condition is False on the
first pass, the statements are never executed.
e.g. The following Do Loop counts from 1 to 100.
Dim number As nteger
number = 1
Do While number <= 100
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

number = number + 1
Loop

While / Wend Statement
A While / Wend statement behaves like the Do While / Loop statement.

e.g.
Dim number As nteger
number = 1
While number <=100
number = number + 1
Wend

Do / Loop While Statement
The Do / Loop While statement first executes the statements and then tests the
condition after each execution. The program executes the statements between Do and
Loop While structure in any case. Then it determines whether the condition is satisfied.
f so, the program again executes the statements between Do and Loop While,
otherwise, it exits the Loop.

e.g.
Dim number As Long
number = 0
Do
number = number + 1
Loop While number < 101

Do Until / Loop Statement
Unlike the Do While / Loop and While / Wend repetition structures, the Do Until /
Loop structure tests a condition for falsity. Statements in the body of a Do Until / Loop
are executed repeatedly as long as the loop-continuation test evaluates to False.

e.g.
Dim number As Long
number = 0
Do Until number > 1000
number = number + 1
Print number
Loop

%he or / Net Loop
The For / Next Loop is another way to make loops in Visual Basic. For / Next
repetition structure handles all the details of counter-controlled repetition.

Dim x As nteger
For x = 1 To 50
Print x
Next
Dim x As nteger
For x = 1 To 50 Step 2
Print x
Next

The above coding will display numbers vertically on the form. n order to display
numbers horizontally the following method can be used.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012



For x = 1 To 50
Print x & Space$ (2);
Next

3.4.5 With / End With Statement
When properties are set for objects or methods are called, a lot of coding is
included that acts on the same object. t is easier to read the code by implementing the
With / End With statement. Multiple properties can be set and multiple methods can be
called by using this statement. The code is executed more quickly and efficiently as the
object is evaluated only once.

With ObjectName
.Property1 = value1
.Property2 = value2
.Property3 = value3
..
.Property_n = value_n
End With

With Text1
.Font.Size = 14
.Font.Bold = True
.ForeColor = vbRed
.Height = 230
.Text = "Hello World"
End With
3.4.6 Nested ControI Structures
You can place control statements inside other control statements, for example an
f / Then / Else block within a For / Next loop. A control statement placed inside another
control statement is said to be nested.
Control structures in Visual Basic can be nested to as many levels as you want.
t is common practice to make nested structures more readable by indenting the body of
each one. The integrated development environment (DE) editor automatically does this.

Dim x As nteger
For x = 1 to 50
f xmod2 = 0 then
Print x
End f
Next

You cannot overlap control structures. This means that any nested structure must be
completely contained within the next innermost structure. For example, the following
arrangement is invalid because the For loop terminates before the inner With block
terminates.

STATSTCS 124: ntroduction to Programming - 1


st
Semester, 2011-2012

The Visual Basic compiler detects such overlapping control structures and signals a
compile-time error.
3.4.7 Exit Do and Exit For statements
Sometimes we need exit to exit a loop prematurely because a certain condition is
fulfilled. To exit a For / Next Loop, you can place the Exit For statement within the loop; the Do /
While loop is terminated using Exit Do statement. The two statements are normally used
together with the f / Then statement.

Dim x As nteger
For x = 1 To 10
Print x
f x = 5 Then
Exit For
Print "The program exited at x=5"
End f
Next
Dim x As nteger
Do While x < 10
Print x
x = x + 1
f x = 5 Then
Print "The program is exited at x=5"
Exit Do
End f
Loop

3.5 Sub Procedures and Function Procedures

3.5.1 ModuIes

Code in Visual Basic is stored in modules. There are three kinds of modules: form,
standard, and class. Simple applications can consist of just a single form, and all of the
code in the application resides in that form module. As your applications get larger and
more sophisticated, you add additional forms. Eventually you might find that there is
common code you want to execute in several forms. You don't want to duplicate the
code in both forms, so you create a separate module containing a procedure that
implements the common code. This separate module should be a standard module.
Over time, you can build up a library of modules containing shared procedures.

Each standard, class, and form module can contain:
O Declarations. You can place constant, type, variable, and dynamic-link library (DLL)
procedure declarations at the module level of form, class or standard modules.
O Procedures. A Sub, Function, or Property procedure contains pieces of code that can
be executed as a unit.

orm Modules
Form modules (.FRM file name extension) are the foundation of most Visual Basic
applications. They can contain procedures that handle events, general procedures, and
form-level declarations of variables, constants, types, and external procedures. f you
were to look at a form module in a text editor, you would also see descriptions of the
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

form and its controls, including their property settings. The code that you write in a form
module is specific to the particular application to which the form belongs; it might also
reference other forms or objects within that application.

Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They can
contain global (available to the whole application) or module-level declarations of
variables, constants, types, external procedures, and global procedures. The code that
you write in a standard module isn't necessarily tied to a particular application; if you're
careful not to reference forms or controls by name, a standard module can be reused in
many different applications.

Class Modules
Class modules (.CLS file name extension) are the foundation of object-oriented
programming in Visual Basic. You can write code in class modules to create new
objects. These new objects can include your own customized properties and methods.
Actually, forms are just class modules that can have controls placed on them and can
display form windows.

3.5.2 Procedures in VisuaI Basic

A procedure is a block of Visual Basic statements enclosed by a declaration statement
(Function, Sub, Operator, Get, Set) and a matching End declaration. All executable
statements in Visual Basic must be within some procedure.


%pes of procedures
O Sub Procedures perform actions but do not return a value to the calling code.
O Event-handling procedures are Sub procedures that execute in response to an
event raised by user action or by an occurrence in a program.
O Function Procedures return a value to the calling code. They can perform other
actions before returning.
O Property Procedures return and assign values of properties on objects or modules.
O Operator Procedures define the behavior of a standard operator when one or both
of the operands is a newly-defined class or structure.
O Generic Procedures in Visual Basic define one or more type parameters in addition
to their normal parameters, so the calling code can pass specific data types each
time it makes a call.

3.5.3 Sub Procedures

A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End
Sub statements. The Sub procedure performs a task and then returns control to the
calling code, but it does not return a value to the calling code. Each time the procedure
is called, its statements are executed, starting with the first executable statement after
the Sub statement and ending with the first End Sub, Exit Sub, or Return statement
encountered.

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

You can define a Sub procedure in modules, classes, and structures. By default, it is
Public, which means you can call it from anywhere in your application that has access to
the module, class, or structure in which you defined it.

The syntax for defining a Sub Procedure is

Sub subname (parameter/s)

When control passes to the procedure, each parameter is treated as a local variable.
This means that its lifetime is the same as that of the procedure, and its scope is the
whole procedure.

3.5.4 Function Procedures

A Function procedure is a series of Visual Basic statements enclosed by the Function
and End Function statements. The Function procedure performs a task and then returns
control to the calling code. When it returns control, it also returns a value to the calling
code. Each time the procedure is called, its statements run, starting with the first
executable statement after the Function statement and ending with the first End
Function, Exit Function, or Return statement encountered.

You can define a Function procedure in a module, class, or structure. t is Public by
default, which means you can call it from anywhere in your application that has access
to the module, class, or structure in which you defined it. A Function procedure can take
arguments, such as constants, variables, or expressions, which are passed to it by the
calling code.

The syntax for declaring a Function procedure is as follows:

[ modifiers ] Function functionname [( parameterlist )] As returntype
Statements of the Function procedure.
End Function

The modifiers can specify access level and information regarding overloading,
overriding, sharing, and shadowing. Each parameter is declared in the same way as
parameters for Sub Procedures.

#eturning Values

The value a Function procedure sends back to the calling code is called its return value.
The procedure returns this value in one of two ways:
O t assigns a value to its own function name in one or more statements of the
procedure. Control does not return to the calling program until an Exit Function or
End Function statement is executed.

Function functionname [( parameterlist )] As returntype
End Function

O t uses the Return statement to specify the return value, and returns control
immediately to the calling program.

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Function functionname [( parameterlist )] As returntype
Return expression
End Function

The advantage of assigning the return value to the function name is that control does
not return from the procedure until it encounters an Exit Function or End Function
statement. This allows you to assign a preliminary value and adjust it later if necessary.

3.5.5 Invoking Procedure caIIs

%o call a Sub procedure

A Sub procedure does not return a value to the calling code. You call it explicitly with a
stand-alone calling statement. You cannot call it by simply using its name within an
expression.

The calling statement can optionally use the Call keyword. This is recommended,
because it improves the readability of your code.

1. Use a Call statement, following the Call keyword with the name of the Sub
procedure.
2. Follow the procedure name with parentheses to enclose the argument list. f there
are no arguments, you can optionally omit the parentheses. However, using the
parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by
commas. Be sure you supply the arguments in the same order that the Sub
procedure defines the corresponding parameters.

%o Call a function !rocedure

A Function procedure returns a value to the calling code. You call it by including its
name and arguments either on the right side of an assignment statement or in an
expression. You can use the Call keyword to call a Function procedure. However, this
technique ignores the value returned by the procedure.

%o call a Function procedure within an expression
1. Use the Function procedure name the same way you would use a variable. You can
use a Function procedure call anywhere you can use a variable or constant in an
expression.
2. Follow the procedure name with parentheses to enclose the argument list. f there
are no arguments, you can optionally omit the parentheses. However, using the
parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by
commas. Be sure you supply the arguments in the same order that the Function
procedure defines the corresponding parameters.
4. Alternatively, you can pass one or more arguments by name.
5. The value returned from the procedure participates in the expression just as the
value of a variable or constant would.

%o call a Function procedure in an assignment statement
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

1. Use the Function procedure name following the equal (=) sign in the assignment
statement.
2. Follow the procedure name with parentheses to enclose the argument list. f there
are no arguments, you can optionally omit the parentheses. However, using the
parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by
commas. Be sure you supply the arguments in the same order that the Function
procedure defines the corresponding parameters, unless you are passing them by
name.
4. The value returned from the procedure is stored in the variable or property on the left
side of the assignment statement.

3.5.6 Exit Sub and Exit functions

The Exit statement allows you to exit directly from any decision structure, loop, or
procedure. t immediately transfers execution to the statement following the last control
statement. The syntax for the Exit statement specifies which type of control statement
you are transferring out of. Exit Sub, Exit Function, and Exit Property can appear as
many times as needed, anywhere within the body of the procedure. They can even
appear inside a control statement such as f...Then...Else. These statements are useful
when a procedure has done everything it needs to do and can return immediately.

Exit Sub mmediately exits the Sub procedure in which it appears. Execution continues
with the statement following the statement that called the Sub.

The Exit Function statement causes an immediate exit from a Function procedure.
Program execution continues with the statement that follows the statement that called
the Function procedure.

3.5.7 Storage cIasses

An identifier's storage class determines the period during which that identifier exists in
memory. Some identifiers exist briefly, some are repeatedly created and destroyed, and
others exist for the entire program execution. A variable's storage class is sometimes
referred to its lifetime.

Storage Class Specifiers

1. Automatic Variables/ Non-static local variables
- are created when the procedure becomes active. Automatic variables exist until
the procedure is exited. Memory allocated for automatic variables is reclaimed by
the system.

2. Static Variables
- are used to declare identifiers for variables and procedures of the static storage
class. For static variables, storage is allocated and initialized once when the form
is created. For static procedures, all variables in the procedure are static
variables.

3.5.8 Scope ruIes

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

The scope of an identifier is the region of a project in which that identifier can be
referenced. For example, when we declare a local variable in a procedure, it can be
referenced only in that procedure.

1. Local Scope applies to variables declared in a procedure's body. Local variables
can be referenced from the point at which they are declared through End Sub. (or
End function)
2. Module Scope applies to variables declared in the general declaration with Dim. By
default, module variables can only be referenced in the module in which they are
declared. Module Scope is sometimes called Private Scope.
3. Public Scope refers to module variables that are declared Public. Module variables
that are Public are accessible to all modules.

3.5.9 Recursion and FactoriaI Functions

A recursive procedure is one that calls itself either directly or indirectly through another
call. n general, this is not the most effective way to write Visual Basic code.

Considerations with #ecursive !rocedures

1. Limiting Conditions - You must design a recursive procedure to test for at least one
condition that can terminate the recursion, and you must also handle the case where
no such condition is satisfied within a reasonable number of recursive calls. Without
at least one condition that can be met without fail, your procedure runs a high risk of
executing in an infinite loop.
2. Memory Usage - Your application has a limited amount of space for local variables.
Each time a procedure calls itself, it uses more of that space for additional copies of
its local variables. f this process continues indefinitely, it eventually causes a
StackOverflowException error.
3. Efficiency - You can almost always substitute a loop for recursion. A loop does not
have the overhead of passing arguments, initializing additional storage, and returning
values. Your performance can be much better without recursive calls.
4. Mutual Recursion - You might observe very poor performance, or even an infinite
loop, if two procedures call each other. Such a design presents the same problems
as a single recursive procedure, but can be harder to detect and debug.
5. Calling with Parentheses - When a Function procedure calls itself recursively, you
must follow the procedure name with parentheses, even if there is no argument list.
Otherwise, the function name is taken as representing the return value of the
function.
6. Testing - f you write a recursive procedure, you should test it very carefully to make
sure it always meets some limiting condition. You should also ensure that you cannot
run out of memory due to having too many recursive calls.


3.6 Working with Arrays

3.6.1 Concepts

An array is a set of values that are logically related to each other, such as the number of
students in each grade in a grammar school. An array allows you to refer to these
related values by the same name and to use a number, called an index or subscript, to
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

tell them apart. The individual values are called the elements of the array. They are
contiguous from index 0 through the highest index value.

When you use arrays, you can refer to multiple values by the same name, using a
number called an index or subscript to distinguish them from one another. Arrays can
shorten and simplify your code, allowing you to create loops that deal efficiently with any
number of elements.

3.6.2 DecIaring Arrays

You declare an array variable the same way as any other variable, by using the Dim
statement. You follow the variable name with one or more pairs of parentheses to
indicate that it is to hold an array rather than a scalar (a variable that contains a single
value).

For fixed-length arrays, you must specify the upper bound of the array; you can
optionally specify the lower bound. By default, the lower bound is 0. For variable-length
arrays, you do not specify any bounds; you just code an empty set of parentheses.

Dim arraname(index) As Datatpe

The preceding syntax declares an array variable but does not assign an array to it. You
still must create a one-dimensional array, initialize it, and assign it to the arraname.

Array DecIaration Notes
Dim aintCount(9) As nteger declares a 10-element array, indexed 0 to 9
Dim aintCount(0 To 9) As
nteger
same as above, with explicit lower bound
Dim aintCount(1 To 10) As
nteger
declares a 10-element array, indexed 1 To 10
Dim aintCount(-4 To 5) As
nteger
declares a 10-element array, indexed -4 To 5
Dim aintCount() As nteger declares a variable-length array whose
bounds will be determined at run-time

%o create an arra in the arra declaration statement

n your declaration, add a new clause after the variable name and its parentheses.

Dim arraname( ) as Datatpe = Variable( ) {initial value}

The new clause must specify the type name, followed by parentheses, followed by
braces, {}. The parentheses do not represent a call to an array constructor. nstead, they
indicate that the object type is an array type. The braces supply initialization values. The
compiler requires the braces even if you are not supplying any values. Therefore, the
new clause must include both the parentheses and the braces, even if they are empty.

STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

%o create an arra in a separate assignment statement

Use a subsequent assignment statement with a new clause.

Dim arraname( ) As Datatpe
Arraname = Variable( ) {initial value}

Use the ReDim Statement (Visual Basic) to not only create an array but initialize its
length.

ReDim arraname( )

3.6.3 Passing Arrays to procedures

You pass an array the same way you pass any other variable. You supply the array
variable name in the appropriate argument when you call the procedure or access the
property.

%o pass an arra to a procedure

1. Ensure that one of the procedure parameters specifies an array with the same rank
(number of dimensions) and element data type.
2. Supply the array variable at the corresponding place in the argument list. Do not
follow the array name with parentheses.

%o return an arra from a unction procedure

1. Specify the array type (rank and element data type) as the return type in the Function
Statement.
2. Within the procedure, declare a local array variable with the same rank and element
data type.
3. nclude this local array variable in the Return Statement. Do not follow the array
name with parentheses.

3.6.4 Sorting Arrays

Sorting Data is one of the most important computing applications. Sorting data is an
intriguing problem that has attracted intense research efforts There are several well-
known sorting algorithms, with names like the Bubble Sort, Shell Sort, Tag Sort, Heap
Sort, and QuickSort. The bubble sort is the simplest to understand, and it provides a
good initial exposure to sorting algorithms. However, it also the slowest and least efficient
of the sorting algorithms not a big deal if you have a relatively small amount of data to
sort, but if you need to sort an array containing thousands of items, you may want to
research one of the faster algorithms.

The basic bubble sort algorithm calls for repeatedly looping through the array to be
sorted, comparing each item to its adjacent item (i.e., first time through, compare item 1
with item 2, second time compare item 2 with item 3, and so on). When the current pair of
two items is compared, if the first of the two items has a higher value than the second of
the two, then the two items are exchanged, or swapped, within the array. The bubble sort
is so named because the smaller values "bubble" their way up to the top of the array.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

(Looking at it another way, a less-commonly used term for this type of sort is the "sinking
sort" because larger values "sink" their way to the bottom of the array.) Due to the way
that successive adjacent comparisons are made, a large value can move down the array
several positions on one pass. On the first pass, the largest value will always sink to its
proper position in the last element of the array; on the second pass, the next largest
value will sink to its proper position in the next-to-last element of the array, and so on.
Meanwhile, on any given pass, a smaller value will move up only one position.

Private Sub BubbleSort(theArray() As nteger)
Dim pass As nteger, compare As nteger, hold As nteger
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
f theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End f
Next compare
Next pass
End Sub

3.6.5 MuItidimensionaI Arrays

An array can have one or more dimension/s. f it has more than one, it is called a
multidimensional array. Note that having multiple dimensions is not the same thing as a
jagged array, which has other arrays as its elements.

The dimensionality or rank of an array corresponds to the number of indices used to
identify an individual element. You can specify up to 32 dimensions, although more than
three is rare. The following example declares a two-dimensional array variable and a
three-dimensional array variable.

Dim populations(200, 3) As Long
Dim matrix(5, 15, 10) As Single

The total number of elements is the product of the lengths of all the dimensions. n the
preceding example, the array 'populations' has a total of 804 elements (201 x 4), and
matrix has 1056 elements (6 x 16 x 11). Each index ranges from 0 through the length
specified for its dimension.

A two-dimensional array is also called a rectangular array.

All arrays inherit from the Array class in the System namespace, and you can access
the methods and properties of Array on any array. The following members of Array can
be useful:
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

O The Rank property returns the array's rank (number of dimensions)
O The GetLength method returns the length along the specified dimension.
O The GetUpperBound method returns the highest index value for the specified
dimension. The lowest index value for each dimension is always 0.
O The Length property returns the total number of elements in the array.
O The Array.Sort method sorts the elements of a one-dimensional array.

Note that GetLength and GetUpperBound take a 0-based argument for the dimension
you are specifying.

3.6.6 Jagged Arrays

An array of which each element is itself an array is called an array of arrays, or a jagged
array. Note that having arrays as elements is not the same thing as a multidimensional
array, which has more than one index on a single array.

Sometimes the data structure in your application is two-dimensional but not rectangular.
For example, you might have an array of months, each element of which is an array of
days. Since different months have different numbers of days, the elements do not form a
rectangular two-dimensional array. n such a case, you can use a jagged array instead
of a multidimensional array.

Dim sales()() As Double = New Double(11)() {}
Dim month As nteger
Dim days As nteger
For month = 0 To 11
days = DateTime.DaysnMonth(Year(Now), month + 1)
sales(month) = New Double(days - 1) {}
Next month

The New clause in the declaration of sales sets the array variable to a 12-element array,
each element of which is of type Double(), an array of Double elements. The For loop
then determines how many days are in each month this year (Year(Now)), and sets the
corresponding element of sales to a Double array of the appropriate size.

n the previous example, the jagged array saves seven elements (six in a leap year) as
compared to a two-dimensional array. n a more extreme case the memory savings
could be significant.

3.6.7 ControI Arrays

Similar to arrays of variables, you can group a set of controls together as an array. The
following facts apply to control arrays:

O The set of controls that form a control array must be all of the same type (all
textboxes, all labels, all option buttons, etc.)
O You set up a control array by naming one or more controls of the same type the
same name and set the ndex property of each control in the array to a non-negative
value (i.e., the controls in the control array are usually indexed from 0 to one less
than the number of controls in the array).
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

O The properties of the controls in the control array can vary: i.e., some members can
be visible or not, they can be sized differently, they can have different fonts or colors,
etc.

To refer to a member of a control array, the syntax is:

ControlName(Index).Propert

For example, to refer to the Text property of the first element of an array of textboxes
called txtField, you would use:

txtField(0).Text

All the members of the control array share the same event procedure; for example, if
you have a control array of 10 textboxes call txtField, indexed 0 to 9, you will not have
10 different events - you will just have one that is shared amongst the 10 members. To
differentiate which member of the control array is being acted upon, VB will
automatically pass an ndex parameter to the event procedure.

3.6.8 Dynamic Arrays

Sometimes you may not know exactly how large to make an array. You may want to
have the capability of changing the size of the array at run time. A dynamic array can be
resized at any time. Dynamic arrays are among the most flexible and convenient
features in Visual Basic, and they help you to manage memory efficiently. For example,
you can use a large array for a short time and then free up memory to the system when
you're no longer using the array.

The alternative is to declare an array with the largest possible size and then ignore array
elements you don't need. However, this approach, if overused, might cause the
operating environment to run low on memory.

%o create a dnamic arra

1. You declare the array as dynamic by giving it an empty dimension list.
Dim arraname( )
2. Allocate the actual number of elements with a ReDim statement.
ReDim arraname(X + 1)

The ReDim statement can appear only in a procedure. Unlike the Dim and Static
statements, ReDim is an executable statement it makes the application carry out an
action at run time.

The ReDim statement supports the same syntax used for fixed arrays. Each ReDim can
change the number of elements, as well as the lower and upper bounds, for each
dimension. However, the number of dimensions in the array cannot change.

!reserving the Contents of Dnamic rras

Each time you execute the ReDim statement, all the values currently stored in the array
are lost. Visual Basic resets the values to the Empty value (for Variant arrays), to zero
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

(for numeric arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of
objects).

This is useful when you want to prepare the array for new data, or when you want to
shrink the size of the array to take up minimal memory. Sometimes you may want to
change the size of the array without losing the data in the array. You can do this by
using ReDim with the Preserve keyword. For example, you can enlarge an array by one
element without losing the values of the existing elements using the UBound function to
refer to the upper bound:

ReDim Preserve arraname(UBound(arraname) + 1)
Only the upper bound of the last dimension in a multidimensional array can be changed
when you use the Preserve keyword; if you change any of the other dimensions, or the
lower bound of the last dimension, a run-time error occurs.

3.6.9 Function Arrays

The VB Array function establishes an array (list) of values. To create a constant array
you define the array name as a variant.

Example:

Dim myArray as Variant
myArray = Array(5,10,15,21)

You can then refer to an array element by its integer position starting at 1:

Msgbox myArray(2)

The Msgbox above will display the number 15


3.7 Menus, Command diaIog Boxes, and Forms

Windows applications provide groups of related commands in Menus. These commands
depend on the application, but some-such as Open and Save -are frequently found in
applications. Visual Basic provides an easy way to create menus with the modal Menu Editor
dialog.

Creating Menus

n an open Visual Basic Project, go to the menu bar and select TooIs >>> Menu Editor. You
may also right-click the form and select Menu Editor from the pop-up that will appear.








STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012


























n the Menu Editor Window you can specify the structure of your menu by adding one
command at a time. Each menu command has two compulsory properties.
O Caption: This is the name that user sees on the application's menu bar
O Name: This is the name of the menu command. This property doesn't appear on the
screen, but is used in programming the function of the menu command.

The Menu Editor dialog also provides several CheckBoxes to control the appearance of the
Menu.
O Checked: This is unchecked by default and allows the programmer the option of creating
a checked menu item (a menu item that act as a toggle and displays a check mark when
selected.
O Enabled: specifies whether a menu is disabled or not. f you see a disabled command in a
menu that means that feature is not available.
O Visible: specifies whether the menu is visible at run-time or not. .

To add commands to the Form's menu bar, enter a caption and a name for each command. As
soon as you start typing the command's caption, it also appears in a new line in the list at the
bottom of the Menu Editor window. To add more commands, click Enter and type the Caption
and the Name.

The programmer can create menu control arrays. The ndex TextBox specifies the menu's
index in the control array.

Creating !op-Up Menus

Move menu down
Move menu up
Add submenu
ndex
Caption
Name
Remove submenu
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

Nearly every windows application provides a context menu (or short cut menu) that the user
can invoke by right clicking the Form or a control. This Pop-Up menu is a regular menu, but it
is not anchored on the Form. t can be displayed anywhere on the Form. Pop-Up menus are
invoked with the PopupMenu method. First, you create a menu as usual. Make sure that your
desired pop-up menu is defined here. Then insert the following line in a control's MouseUp
event:

Private Sub Form_MouseUp(Button As nteger, Shift As nteger, X As Single, Y As_
Single)
f Button = vbRightButton Then
PopupMenu menuname
End f
End Sub

(The MouseUp event is used because, unlike the click event, it specifies which button was
pressed.) f the right mouse button is pressed, the code calls the Form's PopupMenu method
to display the selected menu. The PopupMenu method is usually called from within TextBox
and PictureBox controls, because these controls can carry out editing operations.

f you don't want the selected menu to be displayed in the menu bar, still you must have the
said menu there and what you have to do is uncheck the visibIe box in the menu editor.

dding ccess kes to Menu Commands

The access key for a command is the keyboard key the user can press to execute the
command. When the user opens a menu at runtime, the access key for a command is
indicated by an underlined letter in the command name. To add an access key to a menu
command, all you need to do is start the menu Editor and prefix the access key letter in the
menu item caption with an ampersand (&). From that time forward, your program will support
the access key.

3.8 Debugging VisuaI Basic Programs


O Displaying nformation with the MsgBox

The easiest way to debug a Visual Basic Program is by placing statements in your
program to see what value a certain variable contains.

MsgBox Format(Variable)

Use the following type of statement to see what values var1 and var2 currently take on
(this is also useful for more than two variables):

MsgBox Format (var1) & ": & Format(var2)

O Ctrl + Break

While your program is running in the development environment, you can interrupt it at any
time by pressing Ctrl + Break. This will invoke the Visual Basic debugger.
STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2011-2012

You may also use the immediate window to check on some values and perform basic
tasks. The immediate window allows you to enter a visual basic statement and execute it
immediately. Statements that declare variables or define subroutines can't be used in this
window, but early any other statement can be used.

O Debugging with breakpoints

A breakpoint is a marker in your program that will temporarily interrupt your program and
transfer control to the mmediate Window. To set a breakpoint, simply click on the gray
area to the right of your statement. The statement will be highlighted in brown, and a
brown dot will appear in the gray area. When your program is running and encounters the
breakpoint, the statement is highlighted in yellow, and the code window appears with the
mmediate window. You can then examine any variables local to the procedure and look at
any module-level variables or global variables.



STATSTCS 124: ntroduction to Programming - 1
st
Semester, 2009-2010

44

Sources:

Flowcharting
http://www.nos.org/htm/basic2.htm

Moursund, David G. ntroduction to Computers and Communication. Tata McGraw-Hill, New
Delhi.1978

Polli, Andrea. Programming tools. http://acweb.colum.edu/classes/255501/week2.html.

Programming Languages.
http://www.wqsb.qc.ca/mydestiny/Lesson%20Plans/AdultEd_LessonPlans/Programme_Utility_Software/c
lassnote8.pdf.

Pseudocode Standard. http://users.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html.

http://www.texarkanacollege.edu/~bforward/logpsudo.htm

http://bedardweb.ca/pseudo/

Computer Hardware
http://eup.k12.mi.us/~jpage/Comp_Hardware/comp_hardware.html

Computer Language and System Software.
http://www.northstar.k12.ak.us/schools/lth/departments/cs/Languages.html

Mack, George. A History of Visual Basic and Basic on the PC. May 2004.
http://dc37.dawsoncollege.qc.ca/compsci/gmack/info/VBHistory.htm

Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/getting-know-vb6-ide

S-ar putea să vă placă și