Documente Academic
Documente Profesional
Documente Cultură
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.