INTE 211 Lecture1
INTE 211 Lecture1
Introduction to programming
Programming Languages
Programming languages are collections of commands, statements and words that are combined
using a particular syntax, or rules, to write both systems and application software. This results
in meaningful instructions to the CPU.
A machine language consists of binary digit, that is, zeroes and ones. Instructions and addresses
are written in binary (0,1) code. Binary is the only “language” a CPU can understand. The CPU
directly interprets and executes this language, therefore making it fast in execution of its
instructions. Machine language programs directly instructed the computer hardware, so they
were not portable. That is, a program written for computer model A could not be run on
computer model B without being rewritten. All software in other languages must ultimately be
translated down to machine language form. The translation process makes the other languages
slower.
Advantage
• The only advantage is that program of machine language run very fast because no
translation program is required for the CPU.
Disadvantages
• It is very difficult to program in machine language. The programmer has to know details
of hardware to write program.
• The programmer has to remember a lot of codes to write a program, which results in
program errors.
• It is difficult to debug the program.
Uses symbols and codes instead of binary digits to represent program instructions. It is a
symbolic language meaning that instructions and addresses are written using alphanumeric
labels, meaningful to the programmer.
The resulting programs still directly instructed the computer hardware. For example, an
assembly language instruction might move a piece of data stored at a particular location in RAM
into a particular location on the CPU. Therefore, like their first generation counterparts, second
generation programs were not easily portable.
1
Assembly languages were designed to run in a small amount of RAM. Furthermore, they are
low-level languages; that is the instructions directly manipulate the hardware. Therefore,
programs written in assembly language execute efficiently and quickly. As a result, more
systems software is still written using assembly languages.
The language has a one to one mapping with machine instructions but has macros added to it. A
macro is a group of multiple machine instructions, which are considered as one instruction in
assembly language. A macro performs a specific task, for example adding, subtracting etc. A
one to one mapping means that for every assembly instruction there is a corresponding single or
multiple instructions in machine language.
An assembler is used to translate the assembly language statements into machine language.
Advantages:
The symbolic programming of Assembly Language is easier to understand and saves a
lot of time and effort of the programmer.
It is easier to correct errors and modify program instructions.
Assembly Language has the same efficiency of execution as the machine level language.
Because this is one-to-one translator between assembly language program and its corresponding
machine language program.
Disadvantages:
One of the major disadvantages is that assembly language is machine dependent. A
program written for one computer might not run in other computers with different hardware
configuration.
Third generation languages are easier to learn and use than were earlier generations. Thus
programmers are more productive when using third generation languages. For most
applications, this increased productivity compensates for the decrease in speed and efficiency of
the resulting programs. Furthermore, programs written in third generation languages are
portable; that is, a program written to run on a particular type of computer can be run with little
or no modification on another type of computer. Portability is possible because third generation
languages are “high-level languages”; that is instructions do not directly manipulate the
computer hardware.
Third generation languages are sometimes referred to as “procedural” languages since program
instructions, must still the computer detailed instructions of how to reach the desired result.
2
High-level languages incorporated greater use of symbolic code. Its statements are more
English –like, for example print, get, while. They are easier to learn but the resulting
program is slower in execution. Examples include Basic, Cobol, C and Fortran. They have
first to be compiled (translated into corresponding machine language statements) through the
use of compilers.
Fourth generation languages are even easier to use, and more English-like, than are third
generation languages. Fourth generation languages are sometimes referred to as “non-
procedural”, since programs tell the computer what it needs to accomplish, but do not provide
detailed instructions as to how it should accomplish it. Since fourth generation languages
concentrate on the output, not procedural details, they are more easily used by people who are
not computer specialists, that is, by end users.
Many of the first fourth generation languages were connected with particular database
management systems. These languages were called query languages since they allow people to
retrieve information from databases. Structured query language, SQL, is a current fourth
generation language used to access many databases. There are also some statistical fourth
generation languages, such as SAS or SPSS.
Some fourth generation languages, such as Visual C++, Visual Basic, or PowerBuilder are
targeted to more knowledgeable users, since they are more complex to use. Visual programming
languages, such as visual basic, use windows, icons, and pull down menus to make
programming easier and more intuitive.
Object oriented programs consist of objects, such as a time card, that include descriptions of the
data relevant to the object, as well as the operations that can be done on that data. For example,
3
included in the time card object, would be descriptions of such data such as employee name,
hourly rate, start time, end time, and so on. The time card object would also contain
descriptions of such operations as calculate total hours worked or calculate total pay.
Language translators
Although machine language is the only language the CPU understands, it is rarely used anymore
since it is so difficult to use. Every program that is not written in machine language must be
translated into machine language before it can be executed. This is done by a category of
system software called language translation software. These are programs that convert the code
originally written by the programmer, called source code, into its equivalent machine language
program, called object code.
There are two main types of language translators: interpreters and compilers.
Interpreters
While a program is running, interpreters read, translate, and execute one statement of the
program at a time. The interpreter displays any errors immediately on the monitor. Interpreters
are very useful for people learning how to program or debugging a program. However, the line-
by-line translation adds significant overhead to the program execution time leading to slow
execution.
Compilers
A compiler uses a language translation program that converts the entire source program into
object code, known as an object module, at one time. The object module is stored and it is the
object module that executes when the program runs. The program does not have to be compiled
again until changes are made in the source code.
Algorithm
4
In its most general sense, an algorithm is any set of detailed instructions which results in a
predictable end-state from a known beginning. Algorithms are only as good as the instructions
given, however, and the result will be incorrect if the algorithm is not properly defined.
Examples of Algorithms
An informal definition could be "a set of rules that precisely defines a sequence of operations."[
A computer program is another pervasive example. Every computer program is simply a series
of instructions, which may vary in complexity, and is listed in a specific order, designed to
perform a specific task. Mathematics also uses algorithms to solve equations by hand, without
the use of a calculator. One last example is the human brain: most conceptions of the human
brain define all behavior — from the acquisition of food to falling in love — as the result of a
complex algorithm.
Pseudocode
Syntax
As the name suggests, pseudocode generally does not actually obey the syntax rules of any
particular language; there is no systematic standard form, although any particular writer will
generally borrow style and syntax; for example, control structures from some conventional
programming language. Popular syntax sources include Pascal, BASIC, C, C++, Java, Lisp,
and ALGOL. Variable declarations are typically omitted. Function calls and blocks of code, such
as code contained within a loop, are often replaced by a one-line natural language sentence.
Depending on the writer, pseudocode may therefore vary widely in style, from a near-exact
imitation of a real programming language at one extreme, to a description approaching formatted
prose at the other.
This is an example of pseudocode (for the mathematical game fizz buzz):
5
Fortran style pseudo code
Pascal style pseudo code C style pseudo code:
program fizzbuzz
do i = 1 to 100 procedure fizzbuzz void function fizzbuzz
set print_number to true for i := 1 to 100 do for (i = 1; i<=100; i++) {
if i is divisible by 3 set print_number to true; set print_number to true;
print "Fizz" if i is divisible by 3 then if i is divisible by 3
set print_number to print "Fizz"; print "Fizz";
false set print_number to false; set print_number to false;
if i is divisible by 5 if i is divisible by 5 then if i is divisible by 5
print "Buzz" print "Buzz"; print "Buzz";
set print_number to set print_number to false; set print_number to false;
false if print_number, print i; if print_number, print i;
if print_number, print i print a newline; print a newline;
print a newline end }
end do
Source code
Source code and object code refer to the "before" and "after" versions of a computer program
that is compiled before it is ready to run in a computer. The source code consists of the
programming statements that are created by a programmer with a text editor or a visual
programming tool and then saved in a file. For example, a programmer using the C language
types in a desired sequence of C language statements using a text editor and then saves them as a
named file. This file is said to contain the source code. It is now ready to be compiled with a C
compiler and the resulting output, the compiled file, is often referred to as object code. The
object code file contains a sequence of instructions that the processor can understand but that is
difficult for a human to read or modify. For this reason and because even debugged programs
often need some later enhancement, the source code is the most permanent form of the program.
When you purchase or receive operating system or application software, it is usually in the form
of compiled object code and the source code is not included. Proprietary software vendors
usually don't want you to try to improve their code since this may created additional service costs
for them. Lately, there is a movement to develop software (Linux is an example) that is open to
further improvement and here the source code is provided.
In large program development environments, there are often management systems that help
programmers separate and keep track of different states and levels of code files. For script
(noncompiled or interpreted) program languages, such as JavaScript, the terms source code and
object code do not apply since there is only one form of the code.
6
• Full set of objects - you 'draw' the application
• Lots of icons and pictures for your use
• Response to mouse and keyboard actions
• Clipboard and printer access
• Full array of mathematical, string handling, and graphics functions
• Can handle fixed and dynamic variable and control arrays
• Sequential and random access file support
• Useful debugger and error-handling facilities
• Powerful database access tools
• ActiveX support
• Package & Deployment Wizard makes distributing your applications simple
Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993.
Visual Basic 4.0 released in late 1995 (added 32 bit application support).
Visual Basic 5.0 released in late 1996. New environment, supported creation of ActiveX
controls, deleted 16 bit application support.
Visual Basic 6.0 - released in mid 1998s - some identified new features of Visual Basic 6.0:
• Faster compiler
• New ActiveX data control object
• Allows database integration with wide variety of applications
• New data report designer
• New Package & Deployment Wizard
• Additional internet capabilities.
If you ever used Visual Basic 3, you too could have known everything. Visual Basic 3 was a
reasonably small but powerful language. Visual Basic 4 added classes to the language and made
Visual Basic much more complicated. Versions 4, 5, and 6 added more support for database
programming and other topics such as custom controls, but Visual Basic was still a fairly
understandable language, and if you took the time you could become an expert in just about all
of it.
Visual Basic.NET accelerated the expansion of Visual Basic tremendously. The .NET
Framework added powerful new tools to Visual Basic, but those tools came at the cost of
increased complexity. Associated technologies have been added to the language at an ever -
increasing rate, so, today, it is impossible for anyone to be an expert on every topic that deals
with Visual Basic.
System requirements for Visual Basic depends on the version of Visual basic software. Visual
Basic 6 for windows requires at least Microsoft Windows 95/Windows NT 3.51, 486 processor
7
and a minimum of 16 MB of RAM. A complete installation of the most powerful version of
Visual Basic 6.0, the Enterprise Edition, requires more than 250 MB of Hard Disk space.
Freetutes.com has Visual Basic Tutorials explained with examples and source code. This online
Visual Basic tutorials are intended for programmers of all levels. Whether you are a beginner or
and advanced VB learner you are absolutely here at the right place to learn what you really
should learn. (You will currently find only Visual Basic 6 tutorials. We are working on to
provide you with Visual Basic.NET tutorials and more other IT related tutorials covering
programming, databases, networking, web development etc. Check back now and then for
updated and new lessons from Freetutes.com)
• Menu Bar
• Tool Bar
• Project Explorer
• Properties window
• Form Layout Window
• Toolbox
• Form Designer
• Object Browser
In previous versions of Visual Basic, the IDE was designed as a Single Document Interface
(SDI). In a Single Document Interface, each window is a free-floating window that is contained
within a main window and can move anywhere on the screen as long as Visual Basic is the
current application. But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI)
format. In this format, the windows associated with the project will stay within a single container
known as the parent. Code and form-based windows will stay within the main container form.
8
Figure 1 The Visual Basic startup dialog box
Menu Bar
This Menu Bar displays the commands that are required to build an application. The main menu
items have sub menu items that can be chosen when needed. The toolbars in the menu bar
provide quick access to the commonly used commands and a button in the toolbar is clicked once
to carry out the action represented by it.
Toolbox
The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area. Additional controls can be included in the toolbox by using the
Components menu item on the Project menu. A Toolbox is represented in figure 2 shown below.
9
Control Description
Command Button Used to carry out the specified action when the user chooses it.
Option Button control which is a part of an option group allows the user to
Option Button
select only one option even it displays mulitiple choices.
List Box Displays a list of items from which a user can select one.
Contains a TextBox and a ListBox. This allows the user to select an ietm
Combo Box
from the dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and These controls allow the user to select a value within the specified range of
VScrollBar values
DriveListBox Displays the valid disk drives and allows the user to select one of them.
10
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
used to display images such as icons, bitmaps and metafiles. But less
Image
capability than the PictureBox
Used to link or embed an object, display and manipulate data from other
OLE
windows based applications.
Label Displays a text that the user cannot modify or interact with.
Project Explorer
Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The
Project Explorer as shown in in figure servres as a quick reference to the various elements of a
project namely form, classes and modules. All of the object that make up the application are
packed in a project. A simple project will typically contain one form, which is a window that is
designed as part of a program's interface. It is possible to develop any number of forms for use in
a program, although a program may consist of a single form. In addition to forms, the Project
Explorer window also lists code modules and classes.
Properties Window
11
The Properties Window is docked under the Project Explorer window. The Properties Window
exposes the various characteristics of selected objects. Each and every form in an application is
considered an object. Now, each object in Visual Basic has characteristics such as color and size.
Other characteristics affect not just the appearance of the object but the way it behaves too. All
these characteristics of an object are called its properties. Thus, a form has properties and any
controls placed on it will have propeties too. All of these properties are displayed in the
Properties Window.
Object Browser
The Object Browser allows us to browse through the various properties, events and methods that
are made available to us. It is accessed by selecting Object Browser from the View menu or
pressing the key F2. The left column of the Object Browser lists the objects and classes that are
available in the projects that are opened and the controls that have been referenced in them. It is
possible for us to scroll through the list and select the object or class that we wish to inspect.
After an object is picked up from the Classes list, we can see its members (properties, methods
and events) in the right column.
A property is represented by a small icon that has a hand holding a piece of paper. Methods are
denoted by little green blocks, while events are denoted by yellow lightning bolt icon.
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar -vsb
Modules
12
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single
Form, and the code resides in that Form module itself. As the application grows, additional
Forms are added and there may be a common code to be executed in several Forms. To avoid the
duplication of code, a separate module containing a procedure is created that implements the
common code. This is a standard Module.
Class module (.CLS filename extension) are the foundation of the object oriented programming
in Visual Basic. New objects can be created by writing code in class modules. Each module can
contain:
Declarations : May include constant, type, variable and DLL procedure declarations.
Procedures : A sub function, or property procedure that contain pieces of code that can be
executed as a unit.
These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:
1. Numeric
13
Integer Store integer values in the range of (-32,768) - (+ 32,767)
Double Store large floating value which exceeding the single data type value
store monetary values. It supports 4 digits to the right of decimal point and 15
Currency
digits to the left
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billion
characters
3. Date
Use to store date and time values. A variable declared as date type can store both date and time
values and it can store date values 01/01/0100 up to 12/31/9999
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values and
cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero
value is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a
variable without any data type by default the data type is assigned as default.
- Substract 10-5 5
/ Divide 25/5 5
14
* Multiply 5*4 20
Relational Operators
Logical Operators
Operators Description
AND Operation will be true only if both the operands are true
15
There are many ways of declaring variables in Visual Basic. Depending on where the variables
are declared and how they are declared, we can determine how they can be used by our
application. The different ways of declaring variables in Visual Basic are listed below and
elucidated in this section.
• Explicit Declaration
• Using Option Explicit statement
• Scope of Variables
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new
variable, it assigns the default variable type and value. This is called implicit declaration. Though
this type of declaration is easier for the user, to have more control over the variables, it is
advisable to declare them explicitly. The variables are declared with a Dim statement to name the
variable and its type. The As type clause in the Dim statement allows to define the data type or
object type of the variable. This is called explicit declaration.
Syntax
For example,
Intcount = Intcount + 1
This calculation will result in intcount yielding a value of 1 as intcount would have been
initialized to zero. This is because the intcount variable has been mityped as incont in the right
hand side of the second variable. But Visual Basic does not see this as a mistake and considers it
to be new variable and therefore gives a wrong result.
In Visual Basic, to prevent errors of this nature, we can declare a variable by adding the
following statement to the general declaration section of the Form.
Option Explicit
16
This forces the user to declare all the variables. The Option Explicit statement checks in the
module for usage of any undeclared variables and reports an error to the user. The user can thus
rectify the error on seeing this error message.
The Option Explicit statement can be explicitly placed in the general declaration section of each
module using the following steps.
Scope of variables
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 of the code in our
application 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. If we want a variable to be available to all of the procedures within the same module,
or to all the procedures in an application, a variable is declared with broader scope.
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.
The local variables exist as long as the procedure in which they are declared, is executing. Once
a procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only
as long as the procedure is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains
or preserves value even when a procedure ends. In case we need to keep track of the number of
times a command button in an application is clicked, a static counter variable has to be declared.
These static variables are also ideal for making controls alternately visible or invisible. A static
variable is declared as given below.
Variables have a lifetime in addition to scope. The values in a module-level and public variables
are preserved for the lifetime of an application whereas local variables declared with Dim exist
only while the procedure in which they are declared is still being executed. The value of a local
variable can be preserved using the Static keyword. The follwoing procedure calculates the
running total by adding new values to the previous values stored in the static variable value.
17
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
same value with which it was called. To make all variables in a procedure static, the Static
keyword is placed at the beginning of the procedure heading as given in the below statement.
Example
The following is an example of an event procedure for a CommandButton that counts and
displays the number of clicks made.
The first time we click the CommandButton, the Counter starts with its default value of zero.
Visual Basic then adds 1 to it and prints the result.
A module level variable is available to all the procedures in the module. They are declared using
the Public or the Private keyword. If you declare a variable using a Private or a Dim statement in
the declaration section of a module—a standard BAS module, a form module, a class module,
and so on—you're creating a private module-level variable. Such variables are visible only from
within the module they belong to and can't be accessed from the outside. In general, these
variables are useful for sharing data among procedures in the same module:
You can also use the Public attribute for module-level variables, for all module types except
BAS modules. (Public variables in BAS modules are global variables.) In this case, you're
creating a strange beast: a Public module-level variable that can be accessed by all procedures in
the module to share data and that also can be accessed from outside the module. In this case,
however, it's more appropriate to describe such a variable as a property:
18
You can access a module property as a regular variable from inside the module and as a custom
property from the outside:
The lifetime of a module-level variable coincides with the lifetime of the module itself. Private
variables in standard BAS modules live for the entire life of the application, even if they can be
accessed only while Visual Basic is executing code in that module. Variables in form and class
modules exist only when that module is loaded in memory. In other words, while a form is active
(but not necessarily visible to the user) all its variables take some memory, and this memory is
released only when the form is completely unloaded from memory. The next time the form is re-
created, Visual Basic reallocates memory for all variables and resets them to their default values
(0 for numeric values, "" for strings, Nothing for object variables).
A variable can have the same name and different scope. For example, we can have a public
variable named R and within a procedure we can declare a local variable R. References to the
name R within the procedure would access the local variable and references to R outside the
procedure would access the public variable.
It is easier to debug a program a program with procedures, which breaks a program into discrete
logical limits.
Procedures used in one program can act as building blocks for other programs with slight
modifications.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is
as follows:
19
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures namely general procedures and event
procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure.
• The Code window is opened for the module to which the procedure is to be added.
• The Add Procedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.
• The name of the procedure is typed in the Name textbox
• Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.
• Under Scope, Public is selected to create a procedure that can be invoked outside the
module, or Private to create a procedure that can be invoked only from within the
module.
20
We can also create a new procedure in the current module by typing Sub ProcedureName,
Function ProcedureName, or Property ProcedureName in the Code window. A Function
procedure returns a value and a Sub Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are
especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks
complete within the function.
The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the results.
The above function procedure is written in the general declarations section of the Code window.
A function can also be written by selecting the Add Procedure dialog box from the Tools menu
and by choosing the required scope and type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties for Forms, Standard modules and Class modules.Visual Basic provides three kind
of property procedures-Property Let procedure that sets the value of a property, Property Get
procedure that returns the value of a property, and Property Set procedure that sets the references
to an object.
21
Control Structures in Visual Basic 6.0
Control Statements are used to control the flow of program's execution. Visual Basic supports control
structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop,
While...Wend, For...Next etc method.
If <condition> Then
statement
End If
22
You can use Nested If either of the methods as shown above
Method 1
Method 2
e.g.: Assume you have to find the grade using nested if and display in a text box
23
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single
block of statements from among multiple block of statements. Select...case is more convenient to
use than the If...Else...End If. The following program block illustrate the working of
Select...Case.
e.g.: Assume you have to find the grade using select...case and display in the text box
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 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
Note: In this example I have used a message box function. In later lessons you will learn how to
use message box functions.
A repetition structure allows the programmer to that an action is to be repeated until given
condition is true.
24
Dim number As Integer
number = 1
Do While number <= 100
number = number + 1
Loop
A variable number is initialized to 1 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. If condition is False on the first pass, the statements are
never executed.
number = 1
While number <=100
number = number + 1
Wend
The programs executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statements
between Do and Loop While else exits the Loop.
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.
An example for Do Until...Loop statement. The coding is typed inside the click event of the
command button
25
Dim number As Long
number=0
Do Until number > 1000
number = number + 1
Print number
Loop
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command
button.
Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.
For x = 1 To 50
Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the &
Space$.
Following example is a For...Next repetition structure which is with the If condition used.
26
End If
Next
In the output instead of number 4 you will get the "This is number 4".
Dim x As Integer
For x = 1 To 10
Print x
If x = 5 Then
Print "The program exited at x=5"
Exit For
End If
Next
The preceding code increments the value of x by 1 until it reaches the condition x = 5. The Exit
For statement is executed and it terminates the For...Next loop. The Following statement block
containing Do...While loop is terminated using Exit Do statement.
Dim x As Integer
Do While x < 10
Print x
x=x+1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If
Loop
With Text1
.Font.Size = 14
.Font.Bold = True
.ForeColor = vbRed
.Height = 230
27
.Text = "Hello World"
End With
In the above coding, the object Text1, which is a text box is evaluated only once instead of every
associated property or method. This makes the coding simpler and efficient.
An array is a consecutive group of memory locations that all have the same name and the same
type. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger size
than required. We can declare an array of any of the basic data types including variant, user-
defined types and object variables. The individual elements of an array are all of the same data
type.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of
memory. Arrays may be declared as Public (in a code module), module or local. Module arrays
are declared in the general declarations using keyword Dim or Private. Local arrays are declared
in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
Declaring a fixed-array
28
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6
elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and
upper limit along with the To keyword. An example for this is given below.
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns. To identify a particular
table element, we must specify two indexes: The first (by convention) identifies the element's
row and the second (by convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two dimensions.
Visual Basic supports at least 60 array dimensions, but most people will need to use more than
two or three dimensional-arrays.
It is also possible to define the lower limits for one or both the dimensions as for fixed size
arrays. An example for this is given here.
An example for three dimensional-array with defined lower limits is given below.
29
Basically, you can create either static or dynamic arrays. Static arrays must include a fixed
number of items, and this number must be known at compile time so that the compiler can set
aside the necessary amount of memory. You create a static array using a Dim statement with a
constant argument:
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Most programs don't use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can't be resized during execution. Both these
issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps.
In general, you declare the array to account for its visibility (for example, at the beginning of a
module if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you actually need it,
using a ReDim statement:
If you're creating an array that's local to a procedure, you can do everything with a single ReDim
statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option
Base 1 statement is placed at the beginning of the module. My suggestion is this: Never use an
Option Base statement because it makes code reuse more difficult. (You can't cut and paste
routines without worrying about the current Option Base.) If you want to explicitly use a lower
index different from 0, use this syntax instead:
Dynamic arrays can be re-created at will, each time with a different number of items. When you
re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data
it contains. If you want to resize an array without losing its contents, use the ReDim Preserve
command:
30
ReDim Preserve Customers(2000) As String
When you're resizing an array, you can't change the number of its dimensions nor the type of the
values it contains. Moreover, when you're using ReDim Preserve on a multidimensional array,
you can resize only its last dimension:
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual Basic releases
the memory allocated for its elements (and you can't read or write them any longer); if the array is st
31