Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views27 pages

Introduction To Programmingupdate 2024 5

The document provides an introduction to using arrays in Visual BASIC 6.0, explaining how to define, assign, and access values in arrays using subscripts. It also covers the syntax for reading data from files into arrays and searching for specific values within them. Additionally, it highlights the importance of arrays in programming for managing and processing data efficiently.

Uploaded by

pefib41412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views27 pages

Introduction To Programmingupdate 2024 5

The document provides an introduction to using arrays in Visual BASIC 6.0, explaining how to define, assign, and access values in arrays using subscripts. It also covers the syntax for reading data from files into arrays and searching for specific values within them. Additionally, it highlights the importance of arrays in programming for managing and processing data efficiently.

Uploaded by

pefib41412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Introduction: Visual BASIC 6.

0 Arrays and Tables

grades

Figure 10‑3: Storage Area Named grades

There is still one problem to solve. How do we reference a single one of these storage locations? Remember
grades is the name of all this storage. To differentiate the individual storage locations, BASIC simply
numbers the storage locations allocated when the storage area is defined. Normally, the numbering of
the storage locations begins with 1 and proceeds from left to right giving each other storage location a
number one more than its left neighbor. The number of the storage location is called a subscript. We
now have a model for grades that looks like the one in Figure 10-4.

grades

1 2 3

Figure 10‑4: grades with Subscript Numbering

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com

201 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

10.2 The Syntax of Defining Arrays


To use arrays and subscripts to reference a storage location and/or its contents BASIC uses a two part
syntax. The first part of the syntax explained here is the statement used to allocate a storage area with
properly numbered storage locations. In addition the programmer must tell what kind of information
(Integer, Single, Double, or String) will be put in each location in the array. All locations in an array
must be used for the same kind of data value. Integer values are whole numbers between -32768 and
32767. A Double value is any numeric value that is to be treated as if it contained a decimal point. Both
35 and 35.0 are examples of values of type Double. The value 35 could also be considered of type Integer
but 35.0 could only be considered of type Double. Single is a less flexible data type than Double that
also deals with numeric values containing a decimal point. The syntax for defining an array is:

SYNTAX
Array-Dim Statement
Dim arrayName (num1 To num2) as dataType
arrayName : valid variable name
num1, num2: range of array-subscript range with num1 < num2
dataType Integer, Single, Double, or String
EXAMPLE: Dim grades (1 To 10) as Double
x = grades(2)

Many times the program will allocate more storage locations than needed for a particular instance of
a problem. It will make no difference to BASIC and the program will have the flexibility to be used for
different number of data items without having to change the program. The program is responsible to
keep track of how many storage locations are used regardless of how many are in the range of the array.
Of course, the program cannot try to use more storage locations than are allocated.

10.3 Assigning and Using Values in an Array


In the last section we saw how to allocate a block of memory with a number of storage locations for
holding values of the same type. There were two key parts to the definition. The first was the name of the
whole area allocated. The name for an array is formed following the rules for making a variable name. We
must now see how BASIC accesses a particular one of the storage locations in the area defined in a Dim
statement. The second part of the name for a location in an array is called a subscript and indicates which
location in the array is being referenced. A subscript is included in parentheses following the array name.

Download free eBooks at bookboon.com

202
Introduction: Visual BASIC 6.0 Arrays and Tables

SYNTAX
Array Elements

Dim variable (num1 To num2) as dataType

Individual elements are accessed using a two-part name. The


first is the name of the storage area. The second is the number
of the particular location in the array being referenced written in
parentheses following the array name. The result is a variable name.

EXAMPLE: Dim grades (1 To 10) as Double


grades (2)

The financial industry needs


a strong software platform
That’s why we need you

Working at SimCorp means making a difference. At SimCorp, you help create the tools “When I joined
that shape the global financial industry of tomorrow. SimCorp provides integrated SimCorp, I was
software solutions that can turn investment management companies into winners. very impressed
With SimCorp, you make the most of your ambitions, realising your full potential in with the introduc-
a challenging, empowering and stimulating work environment. tion programme
offered to me.”
Are you among the best qualified in finance, economics,
Meet Lars and other
computer science or mathematics? employees at
simcorp.com/
meetouremployees
Find your next challenge at www.simcorp.com/careers

Mitigate risk Reduce cost Enable growth


simcorp.com

Download free eBooks at bookboon.com

203 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

An example using array elements is shown in Figure 10-5. BASIC automatically initializes storage
locations in arrays containing numeric values to zero.

Dim cost (1 To 5) as Double

cost

0 0 0 0 0

1 2 3 4 5

Assigning Values: cost(1) = 3.86


cost(2) = 4.71
cost(4) = 3.98

cost

3.86 4.71 0 3.98 0

1 2 3 4 5

Using Values: total_cost = 75 * cost(2 ) = 75 * 4.71


ave_cost = (cost(1) + cost(2) + cost(4))/3
= ( 3.86 + 4.71 + 3.98) /3

Figure 10‑5: Using Array Elements

A variable name indicating a location in an array is really no more than a variable name with a slightly
different format because of the subscript. The advantage to an array is that it is easy to access each of
its values by merely changing the value of the subscript. The program in Figure 10-6 shows how arrays
can be used with a For .. Next loop

Download free eBooks at bookboon.com

204
Introduction: Visual BASIC 6.0 Arrays and Tables

Dim surName (1 To 10) as String


Dim carModels (1 To 20) as String
N1 = Val(InputBox(“# surnames”))
For I = 1 To N1
surName(I) = InputBox(“Enter surname:”)
Next I
N2 = Val(InputBox(“# car models”))
For I = 1 To N2
carModels (I) = InputBox(“Enter car model:”)
Next I
Rem Print selected car models & surNames
Print “Output car models”
For I = 1 To N2 Step 3
Print carModels(I)
Next I
Print “Output surnames”
For I = 1 To N1 Step 2
If surName(I) > “M” Then
Print surName(I)
End If
Next I

Figure 10‑6: Arrays and For..Next

On Your Own

1. Allocate a storage area with seven locations numbered 10, 11, … , 16.
2. Allocate a storage area with ten locations numbered 0, 1, 2, … , 8, 9.
3. Allocate a storage area with eight locations numbered 2, 3, …, 9. Assign 1, 3, 5, 7, 9, 11, 13,
and 15 to these locations starting with 1 in location 2.
4. Allocate a storage area with seven location numbered 1, 2, … , 7 with 3* location number as
an initial value.

10.4 Finding the Average and the Standard Deviation


Now that we have the tools to use an array, it is instructive to see how the program we used to introduce
the idea of an array can be written using this new feature. The program similar to the program shown
in Figure 10-2 is shown in Figure 10-7. The difference is that this program uses both the average and
the standard deviation to identify special values.

Download free eBooks at bookboon.com

205
Introduction: Visual BASIC 6.0 Arrays and Tables

A Dim grade (1 To 10) as Integer


sum = 0 : sumSq = 0
N = Val(InputBox(“Enter Number of Grades”))
For I = 1 to N
B grade(I) = Val(InputBox(“Enter a grade”))
sum = sum + grade(I)
sumSq=sumSq + grade(I)^2
Next I
ave = sum / N : stDev = sqr(1/N* sumSq – ave^2)
Print “Grades > “;ave + Stdev
For I = 1 To N
C If grade(I) > ave + stDev Then
Print grade(I)
End If
Next I

Figure 10‑7: Grade Program Using an Array

In A the array is defined. Notice the program could be used for larger data sets as the array is defined
to contain ten locations numbered from 1 to 10. In B the program reads the data and stores each data
value in a different location in the array grade. The code also accumulates the values needed to compute
both the average and the standard deviation of the grades. Finally, in C the program revisits the elements
of grade to determine which of the values are larger than the average plus one standard deviation. (The
standard deviation measures how values cluster around the average.)

10.5 File Input


The model for using arrays to this point will normally require using InputBox() to assign values to
array locations each time a program is run to enter the data. With applications using arrays it is often
the case that there is a lot of data to process. Entering each data value using the InputBox() approach
is very time consuming and can be quite prone to error. To make dealing with large amounts of data
more convenient, a very restricted version of file input will be shown. The model given can be used with
any program but is most useful with entering values into an array. The programs you write can take
the block of code that is introduced and just copy it into a program whenever file input is needed. The
only other problem to deal with is how to create a file for the data. A file can be created in Word if the
result is saved as having type txt. You can choose this file format option in Word in the Save As Type
pull down menu when you go to save the data file.

Download free eBooks at bookboon.com

206
Introduction: Visual BASIC 6.0 Arrays and Tables

For use in this book we use a very special format for the data files so the input code template is simpler.
The restriction on the format of a data file is that the first value must be the number of data items. The
data items follow one after another after the initial number of data items entry with each entry in the
file separated from the next (including the number of data items from the first data item) by a comma.
Suppose the data consists of five values: 4, 7, 5, 2, 9. The file would be created as:

5,4,7,5,2,9

and saved as filename.txt. The syntax and code used to enter a data file so that each value is in a different
location in an array has a different syntax from the InputBox() function.

SYNTAX
Read From A File

Open “filespec” for Input as #n

Input #n, N
For I = 1 To N
Input #n, dataValue(I)
Next I
Close #n

filespec: path name to file


n: an integer value
dataValue(): arrary and subscript
Close: releases the link from BASIC to the file

EXAMPLE: Open “PATH\dataFile.txt” for Input as #1


Input #1, noElements
For I = 1 To noElements
Input #1, dataValue(I)
Next I
Close #1

The Open statement makes a connection between the data file and the BASIC program by telling the
program how to access the data file in the local file space. For purposes of our use the filename will be
of one of the forms:

\\netspace\students\init\logon\public\filename.txt

\\netspace\departments\computer_science\public\filename.txt

Download free eBooks at bookboon.com

207
Introduction: Visual BASIC 6.0 Arrays and Tables

In the first path, init is the first letter of your surname and the logon is your user name. The file filename.
txt will be whatever file is used in the program. Obviously, if you are not using this file system, you
will have to determine the filespec in terms of your computing environment. In Windows you can use
Windows Explorer to find the path you need BASIC to know. In general, the filespec will be shortened
as PATH\filename.txt where you will need to replace PATH with what is appropriate for your file system.
The code you will actually use to access the elements in a data file is shown in Figure 10-8.

Dim arrayName (1 To 100) as Double


Open “PATH\dataFile.txt” for Input as #1
Input #1, N
For I = 1 To N
Input #1, arrayName(I)
Next I
Close #1

Figure 10‑8: Code to Enter Data into an Array from a File

The block of code shown in Figure 10-8 can be used for any array input operation needed by just forming
PATH and using the appropriate dataFile.txt name. Once the PATH is used in the Open statement, it is
not referenced again in the program.

Download free eBooks at bookboon.com

208 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

10.6 Using Arrays – Searching an Array


Once an array is assigned values, a common operation for a user to request is to find out if some value
is in one of the array locations. This operation is called searching an array. The code to carry out the
search of an array is shown in Figure 10-9.

Rem Determine if a value is stored in an array and returns its location if found
Rem INPUT: An array with N elements and and a value to search for
Rem OUTPUT: The location of the element in the array or message “NOT FOUND”
A Dim elements (1 To 100) as Double
Open “PATH\dataFile.txt” for Input as #1
Input #1, N
For I = 1 To N
Input #1, elements(I)
Next I
B Close #1
C searchElement=Val(InputBox(“Enter value to be found”))
location = -1
For I = 1 To N
D If searchElement = elements(I) Then
location = I
GoTo L1
End If
Next I
E L1: If location = -1 Then
Print searchElement; “ NOT FOUND.”
Else
Print searchElement; “ was found at location:”;location
End If

Figure 10‑9: Search Code

The code from A to B dimensions an array and reads a file into the array. The element that is the object
of the search is entered by the user at C. In D the program examines each entry in the array to see if any
of the elements match the element sought. The transfer to E when the element is found lets the program
avoid searching additional array locations when the answer is known. If the element is not found, after
the whole array is searched, control passes to E with location still having its initial value of -1.

10.7 Using Arrays – Finding a Smallest Element in an Array


Putting the elements in an array in increasing or decreasing order is called sorting. To understand a
simple sorting program, there are two parts of the process that need to be explained. In this section we
examine the problem of finding the smallest element in some range of subscripts. In the next two sections
we finish our exploration of sorting. In Figure 10-10 we show how to find a smallest element in an array.

Download free eBooks at bookboon.com

209
Introduction: Visual BASIC 6.0 Arrays and Tables

Rem Find the smallest element in an array


Rem INPUT: The number of string elements and the strings
Rem OUTPUT: The smallest value in the array

A Dim stringElements (1 To 100) as String


B Open “PATH\dataFile.txt” for Input as #1
Input #1, N
For I = 1 To N
Input #1, stringElements(i)
Next I
C Close #1
D smallest = 1 ‘first estimate of location of answer
For I = 2 To N
If stringElements(smallest) > stringElements(I) Then
smallest = I
End If
E Next I
F Print smallest, stringElements(smallest)

Figure 10‑10: Finding a Smallest Element

In A the program defines an array which can hold up to 100 elements of type String. A file of elements
is identified and its elements are input into the array in the code from B to C. The code from D to E
compares each element successively in the array with the smallest element encountered to that point. If
an element is found that is smaller than the smallest to that point, we update the location of the smallest
element encountered so far. When we get to F, the location in smallest gives the location of the smallest
element in the array. The smallest means the least element in the array as determined by the ordering
relation on that type of element. The ordering could be either the natural numeric ordering for numbers
or the dictionary ordering for strings.

10.8 Using Arrays – Interchanging Two Elements in an Array


In the process of sorting we first find the smallest element in the array and then interchange it with the
element in the first location. When we finish, the smallest element is in the first location of the range
searched and the original element in that location is now in the location that originally contained the
smallest element in the range. Figure 10-11 shows the general process of interchanging two elements in
an array where one is located location J = 2 and the second at location K = 5. Interchanging two elements
need not involve the smallest element in a range of subscripts as we see in this example.

Download free eBooks at bookboon.com

210
Introduction: Visual BASIC 6.0 Arrays and Tables

YDOXHV
25,*,1$/      
     
     
     
 -   . 

YDOXHV
$)7(5,17(5&+$1*(      
     
     
     
 -   . 
Figure 10‑11: Interchanging Two Elements in an Array

To interchange two elements in an array, we must know the location of each of the values, say J and K.
It is tempting to write the following code to interchange the elements at these two locations:

elements(J) = elements(K)
elements(K) = elements(J)

If we trace this code for the original values:

elements(J) = 18
elements(K) = 9

we first assign elements (K) to elements (J) giving

elements(J) = 9

If we now assign elements(J) to elements(K) we get

elements(K) = 9.

The difficulty arises because the value of elements(J) is changed to the original value in elements(K)
before we assign the contents of elements(J) to elements(K). The solution to the problem of actually
interchanging two elements is to assign the original value of elements(J) to a separate variable before
we assign the value in elements(K) to elements(J). We can then assign the value in the separate variable
to elements(K) and get the two elements interchanged as we intended. The code to solve this problem
is shown in Figure 10-12.

Download free eBooks at bookboon.com

211
Introduction: Visual BASIC 6.0 Arrays and Tables

Rem Interchange two elements in an array. Print the array before


Rem and after the interchange
Rem INPUT: An N element array and two locations of elements
Rem to interchange
Rem:OUTPUT: The array before and after the interchange
A Dim elements (1 To 100) as Integer
Open “PATH\dataFile.txt” for Input as #1
For I = 1 To N
Input #1, elements(I)
Next I
Close #1

B For I = 1 To N
Print I, elements(I)
Next I
C J=Val(InputBox(“First interchange location”))
K=Val(InputBox(“Second interchange location”))

Print J,elements(J), K, elements(K) ‘original places for elements


D temp = elements(K)
elements(K) = elements(J)
elements(J) = temp

Print J,elements(J), K, elements(K) ‘see what has changed


E For I = 1 To N
Print elements(I)
Next I

Figure 10‑12: Interchanging Two Elements in an Array

Starting at A the array is defined and the file of elements is read into the program. The loop starting at
B is simply a printing of the elements in the original order. The two values entered at C are the array
locations whose elements need to be interchanged. In the code starting with D the actual interchange
takes place. Notice the use of the variable temp. The loop starting at E prints the array with the two
elements interchanged.

10.9 Using Arrays – Sorting an Array


For the sorting process we will use a simple algorithm that has two major steps that are repeated. The
two steps are first to find the smallest element in a range of storage locations and then interchange
that smallest value found with the first element in that range of locations. Since we build up a sorted
array one element at a time, we will need to repeat this process with an increasingly smaller number of
elements in the search area until all the elements are in sorted order. The coding tool we use is a nested
For .. Next construct.

Download free eBooks at bookboon.com

212
Introduction: Visual BASIC 6.0 Arrays and Tables

For the sorting process we first need to find the smallest element in the array and put that element in
location 1. The second step is to find the smallest value remaining in locations 2, 3, … , N and put that
element in location 2. The key is to have a smaller range of locations to search each step so previously
found smallest elements are not found again! We show an example for an array with four elements in
Figure 10-13.

Figure 10‑13: Minimum Selection Sorting Example

Download free eBooks at bookboon.com

213 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

The code that actually carries out the sorting is shown in Figure 10-14.

Rem Sort an array with N elements


Rem INPUT: The number of elements in an array and the elements
Rem OUTPUT: The N elements of the array in increasing order

Dim values (1 To 100) as Double


Open “PATH\dataFile.txt” for Input as #1
Input #1, N
For I = 1 To N
Input #1, values(I)
Next I
Close #1

A For I = 1 to N – 1
smallLocation = I ‘first estimate of location ofanswer
For J = I + 1 to N
B If values(J) < values(smallLocation) Then
smallLocation = J
End If
Next J
temp = values(I)
C values(I) = values(smallLocation)
values(smallLocation) = temp
Next I
For I = 1 To N
D Print values(I)
Next I

Figure 10‑14: Minimal Selection Sort

In A we set the loop control so that the minimal search process is repeated N – 1 times. When I = N-1
we are comparing the elements at N-1 and N. When this loop is finished both of these elements are in
increasing order. Consequently, we do not have to repeat the body of the loop when I = N. (There are
no elements in locations past location N so the element in location N is the smallest element in the
range of N to N!!) B is looking for the smallest element in the range I + 1, …, N as we start the process
saying that the smallest element is in location I. We update out estimate of the location of the smallest
element by comparing each element in the search range with the best estimate found to that point of
the search. When I = 1, we compare elements at 2, 3, … , N. When I = 2, we compare elements at 3,
4, … , N. As I increases, the number of elements in the search range decreases. The interchange that
puts the smallest element in location I is carried out at C. In D the array has its elements printed out
after the sort is completed.

Download free eBooks at bookboon.com

214
Introduction: Visual BASIC 6.0 Arrays and Tables

10.10 Using Arrays – Finding a Distribution of Elements


Since arrays are used to store many data values, it is often useful to find out how the data is distributed
over the range of all the data. This idea is used to find out how many values fall in each bracket of a
decomposition of the range of values. There are several ways we can define the brackets of a decomposition
for integer values. In this example we are looking for how many values in an array with elements in the
range 0-100 are in each of the following intervals:

Brackets

88–100 80–87 73–79 60–72 0–59

1 2 3 4 5

Table 10-1: Brackets for a Distribution

The brackets are given and can be quite different for different applications and different data sets. One
method to find out how many values are in each bracket uses the Multi Case If . The selection code is
shown in Figure 10-15 with the bottom value of Brackets(I) in elements where I ranges from 1 to 5. The
number of elements in a bracket is counted in the array categories.

Download free eBooks at bookboon.com

215 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

For I = 1 To N
If elements (I) >=88 Then
categories(1)=categories(1)+1
ElseIf elements (I) >= 80 Then
categories(2)=categories(2)+1
ElseIf elements (I) >= 73 Then
categories(3)=categories(3)+1
ElseIf elements (I) >= 60 Then
categories(4)=categories(4)+1
Else
categories(5)=categories(5)+1
End If
Next I

Figure 10‑15: Multi Case If Categorization of Data

The If .. ElseIf statement is really quite involved. If a value is found to be less than 88, it will be compared
with 80. The interesting aspect to this syntax is that if the comparison with 88 is false, we know that
the element is not in the interval 88–100. This means the next condition is true if the element is in the
interval 80–87 even though it looks like we are asking if the value is in the range 80–100. Checking on
the upper bound for an interval is unnecessary but is implied since the conditions ask about the bottom
value in a bracket having eliminated all brackets above the one with this bottom value.

A second alternative used for finding a distribution uses a sequence of compound conditions to determine
the categories. The code for this approach is shown in Figure 10-16.

For I = 1 To N
If elements (I) >=88 Then
categories(1)=categories(1)+1
End If
If elements (I) >= 80 And elements (I) <= 87Then
categories(2)=categories(2)+1
End If
If elements (I) >= 73 And elements(I) <=79Then
categories(3)=categories(3)+1
End If
If elements (I) >= 60 And elements(I) <=72Then
categories(4)=categories(4)+1
End If
If elements(I) <= 59 Then
categories(5)=categories(5)+1
End If
Next I

Figure 10‑16: Selection Using Compound Conditions

Download free eBooks at bookboon.com

216
Introduction: Visual BASIC 6.0 Arrays and Tables

10.11 Using Arrays – Parallel Arrays


Problems using arrays have focused on computing with a single set of related values. Even with the
problem of finding the average of a set of numbers, there is often other information related to each value
that must be used in the problem solution. For example, suppose a set of grades is stored in an array
named grades and the corresponding set of student names is to be stored in an array named student. To
find the name of the student with the highest grade requires we know which grade belongs to which
student. It is certainly possible to have one array store the grades and another array store the names. The
issue is that if location I in grades contains a grade that it should be easy to find the name of the student
whose grade it is. The simplest solution is to enter a grade and a name so that the subscript used to
identify the location in grades is also used to identify the location in student where that student’s name
will be stored. The process of coordinating the use of storage locations in two or more arrays is known
as using parallel arrays.

- ste
the of th + -c + in + + ity

Be a part of the equation.


RMB Graduate Programme applications are now open.
Visit www.rmb.co.za to submit your CV before the 23rd of August 2013.

Download free eBooks at bookboon.com

217 Click on the ad to read more


Introduction: Visual BASIC 6.0 Arrays and Tables

The problem solved in Figure 10-2 can be expanded using parallel arrays to identify not only the grades
greater than the average but also the names of the students with a grade greater than the average. See
Figure 10-17.

Dim student (1 To 50) as String


Dim grade (1 To 50) as Integer
sum = 0 ‘accumulator
N = Val(InputBox(“Enter number of values.”))
For I = 1 to N
student(I) = InputBox(“Enter student’s name:”)
grade(I) = Val(InputBox(“Enter a grade”))
sum = sum + grade(I)
Next I
ave = sum / N
For I = 1 To N
If grade(I) > ave Then
Print student(I),grade(I)
End If
Next I

Figure 10‑17: Using Parallel Arrays for Grades and Names

10.12 Using Arrays – Drawing A Pie Chart


The tools we learned in Chapter 9 about drawing capabilities in BASIC can be used in more complex
problems when we use arrays. The problem of displaying data using a pie chart is modified here by using
an array to keep track of the size of each sector in terms of the percentage of the total area of the circle.

Example 10‑1. Write a program that creates a pie chart with three sectors. The user enters the size of
two sectors, and the chart is created based on that data.

SOLUTION:

The sector sizes have been input to be 20% and 35%. The third sector will have size 100 – 20 – 35%.

Download free eBooks at bookboon.com

218
Introduction: Visual BASIC 6.0 Arrays and Tables

Rem Create a pie chart with three sectors. The size of


Rem the sectors are based on the user’s data.
Rem INPUT: Percent of circle representing size of some sectors
Rem OUTPUT: A pie chart with three sectors
Dim sector (1 To 10) as Double
Cls
Rem Get input
A For I = 1 To 2
sector(I) = Val(InputBox(“Enter sector size:”))
Next I

sector(3) = 100 – sector(1) – sector(2)


Rem Initialize variables
B pi = 3.14159
radius = 80
stopangle = .001
Rem Draw each sector
C For I = 1 To 3
If I = 1 Then
FillStyle = 3
FillColor = vbBlue
ElseIf I = 2 Then
FillStyle = 5
FillColor = vbGreen
Else
FillStyle = 7
FillColor = vbYellow
End If
Rem Calculate position and size of current sector
D angle = 2 * pi * sector(I)/100
E startangle = stopangle
stopangle = startangle + angle
If stopangle > 2 * pi Then
stopangle = .001

End If
Rem Draw the sector
F Circle (160, 100), radius,,-startangle,-stopangle
Next I

Download free eBooks at bookboon.com

219
Introduction: Visual BASIC 6.0 Arrays and Tables

COMMENTS: The program begins by allowing the user to input two of the sector sizes at A. Beginning
in B, variables that will be used later are initialized. The For .. Next loop beginning in C draws each
sector individually. Within the loop, D merely computes the appropriate sector size to draw in radian
measure. Beginning in E, equations are used to calculate the size and position of the sector currently
being drawn. The Circle command at F actually draws the sector. The radius of the sector is the radius
that was initialized at B. The color and style of the sector is given by the values assigned to FillColor
and FillStyle in the If block beginning at C.

On Your Own

1. Write a program that creates a pie chart with four sectors. Let three of the sector sizes be
20%, 25%, and 15%. The fourth sector is the remaining portion of the circle. Use any colors
and fill styles.

10.13 Using Arrays – Drawing a Histogram


When values need to be seen in comparison to other values as the sales for a sequence of months or the
number of gyzmos sold each month, the chart often used is a histogram. A histogram represents a set of
values using as a scale the relative difference in the magnitudes. The output form shown here displays a
histogram for values collected over a period of four months denoted by J(anuary), F(ebruary), M(arch),
and A(pril). We see the output for this problem in Figure 10-18.

Figure 10‑18: A Histogram

The code to draw this chart is given in Example 10-2

Example 10-2. Draw a histogram representing the four values 120, 200, 90, and 250 that represent sales
in January, February, March, and April, respectively. Scale the values so that 120 is represented by 24,
200 by 40, 90 by 18, and 250 by 50. Use the labels J, F, M, A for the four months.

Download free eBooks at bookboon.com

220
Introduction: Visual BASIC 6.0 Arrays and Tables

SOLUTION:
Rem: Draw a histogram with four values
Rem INPUT: Four values to be represented
Rem OUTPUT: Histogram representing the relative size of the input numbers
Dim heightValue (1 To 10) as Integer
Dim label (1 To 10) as String

Line (100, 300) – (100, 100)


Line (100, 300) – (250, 300)
Rem Tic mark on the down axis-each tic represents 4 units
For I = 1 to 20
Line (98, 300 – 10 * I)-(102, 300 – 10 * I)
Next I
Rem Enter heights and labels
For I = 1 to 4
heightValue(I) = Val(InputBox(“Enter height”))
label(I) = InputBox(“Box label”)
Next I
Rem Draw and label rectangles
For I = 1 to 4
Line (120 + 30 * (I – 1), 300) – (140 + 30 * (I – 1), 300 – 3 * heightValue(I)), ,B
CurrentX = 125 + 30 * (I – 1) : CurrentY = 312
Print label(I)
Next I

10.14 Putting It All Together


1. Input five numbers into an array using a For .. Next loop. Then using another loop, print
the values in the array.
2. Read ten values into an array using a For .. Next loop. In a second For .. Next loop add
these numbers and finally print the average of the ten numbers.
3. Read N numbers from a file and store them in an array. Count the number of values that are
bigger than the average value.
4. Count the number of values that are less than the average minus 8, the number between
(inclusive) the average plus 8 and the average minus 8, and the number greater than the
average plus 8. Read the values from a file into an array. Use variables ct1, ct2, and ct3 to
store the counts. Print the number of values in each category.
5. Repeat problem 4 but store the counts in an array ave with three storage locations. Print the
values in ave using a For .. Next loop. Print the values on a single line.
6. Modify the code in Figure 10-17 so that there are three parallel arrays. The first array holds
the size of the sectors. The second array at the same index holds the FillStyle value for this
sector. The third array at the same index holds the FillColor value for this sector. Run the
program for a five sector pie chart.

Download free eBooks at bookboon.com

221
Introduction: Visual BASIC 6.0 Arrays and Tables

7. Modify the code in Example 10-2 so that up to seven bars can be included in the histogram.
Use parallel arrays for the bar heights and the bar labels. Use files for the input into the
arrays. Experimental data is often “smoothed” before it is used. The “smoothing” process
replaces each value by the average of the three points that precede it. For example, for a
data file with N elements in an array rawData a new array smoothData is defined and given
values as follows:

smoothData(1) = 0
smoothData(2) = 0
smoothData(3) = 9
smoothData(4) = (rawData(1) + rawData(2) + rawData(3)) / 3

In general,for 4 < I < N define

smoothData(I) = (rawData(I) + rawData(I – 1) + rawData(I – 2) / 3.

Write a program that smoothes data in a file with 25 random numbers in the range 0-18. Output
the results in a table with three columns with titles I, rawData(I), smoothData(I).

8. Experimental data is often “smoothed” before it is used. The “smoothing” process replaces
each value by the weighted average of the three points that precede it. For example, for a
data file with N elements in an array rawData a new array smoothData is defined and given
values as follows:

smoothData(1) = 0
smoothData(2) = 0
smoothData(3) = 9
smoothData(4) = (rawData(1) + rawData(2) * 2 + rawData(3) *3) / 3

In general, for 4 < I < N define

smoothData(I) = (rawData(I – 1) + rawData(I – 2) * 2 + rawData(I – 3) * 3) / 3.

Write a program that smoothes data in a file with 25 random numbers in the range 0-18. Output
the results in a table with three columns with titles I, rawData(I), smoothData(I).

Download free eBooks at bookboon.com

222
Introduction: Visual BASIC 6.0 Index

Index
biased coin, 148
binary code, 78
body of the loop, 123
algorithm, 27 box, 179
alphabet, 78 box filled, 179
ampersand (&), 67 branching, 101
And, 88 conditional, 101, 106
arc, 185 unconditional, 101, 102
arithmetic operations built in function, 63
order, 59 Abs(), 63
priority, 59 Exp(), 63
array, 200 Int(), 153
distribution of elements, 215 Log(), 63
parallel, 217 Mod, 99
search, 209 Rnd, 142
smallest element, 209 Sqr(), 63
ASCII-8, 78, 81 Cls, 31
aspect, 189 code, 27
assignment statement, 47 colon (:), 102
asterisk, 60 color, 176, 179
BackColor, 165 color constants, 164

The next step for


top-performing
graduates

Masters in Management Designed for high-achieving graduates across all disciplines, London Business School’s Masters
in Management provides specific and tangible foundations for a successful career in business.

This 12-month, full-time programme is a business qualification with impact. In 2010, our MiM
employment rate was 95% within 3 months of graduation*; the majority of graduates choosing to
work in consulting or financial services.

As well as a renowned qualification from a world-class business school, you also gain access
to the School’s network of more than 34,000 global alumni – a community that offers support and
opportunities throughout your career.

For more information visit www.london.edu/mm, email [email protected] or


give us a call on +44 (0)20 7000 7573.
* Figures taken from London Business School’s Masters in Management 2010 employment report

Download free eBooks at bookboon.com

223 Click on the ad to read more


Introduction: Visual BASIC 6.0 Index

comma ElseIf, 93
end of Print statement, 34 encapsulation, 126
comment, 28 exponential notation, 68
comparisons, 75 expression, 45, 58
numeric, 76 numeric, 45
string, 78 parenthesised, 62
compound condition, 88 string, 45
concatenation, 67 false range, 86
condition, 84 FillColor, 190
conditional statement, 83 FillStyle, 190
control variable, 123 font_height, 38
range, 124 font_width, 38
convention For .. Next loop, 121
coding, 29 ForeColor, 165
spacing, 84, 127 Format(), 68
counter, 123 $, 69
currency, 69 0, #, @, 70
CurrentX, 38 comma, 69
CurrentY, 38 currency, 69
data percent, 70
numeric, 45 standard, 70
string, 45 GoTo, 102
data file, 207 histogram, 195, 220
data type, 202 I f.. Then .. End If, 83
Double, 202 If Then Else End If, 86
Integer, 202 increment, 123, 129
Single, 202 indenting, 29
String, 202 Int(), 153
decision making, 75 Integer, 202
default position, 38 interchange elements, 210
demand curve, 134, 135 keyword, 27, 46, 84
dialog box, 49 letters
dictionary ordering, 79 lowercase, 81
digits uppercase, 81
left of decimal point, 69 Line, 176
right of decimal point, 69 line labels, 101
Dim, 202 literal, 45
Dimension (Dim), 202 numeric, 45
distribution of elements, 215 string, 45
Double, 202 logical operations
ellipse, 189 And, 88
Else, 86 Not, 88

Download free eBooks at bookboon.com

224
Introduction: Visual BASIC 6.0 Index

Or, 88 prompt and echo, 113


looping, 121 PSet(), 165
marker, 84 radius, 220
Else, 85 random number, 142
End If, 84 scaling, 153
For, 123 Randomize, 144
If, 84 range, 209
Next, 123 counter, 124
Then, 84 relational operator, 76
To, 123 string, 82
Mod, 99 relational operators, 76, 82
negation, 60 Rem, 28, 29
non-executable, 28 RGB(), 164
normalized representation, 68 Rnd, 142
Not, 88 scaling, 153
numeric data, 45 scientific notation, 143
numeric variable, 45 search an array, 209
numerical operation, 58 sector, 188
operations seed, 144
concatenation, 67 semantics, 47
hierarchy, 59 assignment, 47
mathematical, 58 branching, 108
numerical, 58 Cls, 31
priority, 59 For .. Next, 121, 123
operator (&), 114 For .. Step .. Next, 129
Or, 88 GoTo, 102
outcome If .. Then .. Else .. End If, 86
equally likely, 146 If .. Then .. ElseIf .., 95
output display, 38 If .. Then .. End If, 84
output form, 38 InputBox(), 49
output menu, 54 repetition, 109
parallel arrays, 217 Val(), 53
parentheses, 61 variable name, 45
pie chart, 163, 194, 218 semicolon, 33
pixel, 38, 163 end of Print statement, 35
Print, 51 sentinel, 110
comma, 34 simulation, 158
positioning output, 38 Single, 202
semicolon, 33 single quote, 30
print zone, 34 slope, 170
procedure, 27 smallest element, 209, 210
prompt, 49 sort, 209, 212

Download free eBooks at bookboon.com

225
Introduction: Visual BASIC 6.0 Index

statement Line..BF, 179


assignment, 47 Open, 207
comment, 28 path name, 207
Step, 128 Print, 35
string, 78 Pset ( , ), color, 166
String, 202 Randomize, 145
string comparisons, 78, 82 Rem, 30
string constant, 45 Rnd, 143
string data, 45 sector, 188
string variable, 45 Val(), 54
subexpressions variable name, 46, 203
arithmetic, 62 true range, 84
subscript, 201 truth table, 89
subscript range, 202 And, 89
supply curve, 134, 135 Not, 90
symbol overloading, 61 Or, 90
symbolic constant, 45 user friendly interface, 41
SYNTAX, 27 user interrogation technique, 118
arc, 185 Val(), 53
aspect, 190 value
assignment, 48 boolean, 75
Circle, 183 logical, 75
Cls, 31 string, 45
concatenation, 67 variable, 45, 46
CurrentX, 40 variable name, 45
CurrentY, 40 window size, 34
Dim(ension), 202 word, 45, 78
ellipse, 190 zone, 34
FillColor, 192
FillStyle, 192
Fo r.. Next loop, 122
For .. Next, 123
For..Next with step, 129
Format(), 68
GoTo, 102
If .. Then .. Else .. End If, 85
If .. Then .. ElseIf, 95
If .. Then .. End If, 84
Input, 207
InputBox(), 50
Line, 176, 179
line label, 102

Download free eBooks at bookboon.com

226
Introduction: Visual BASIC 6.0 Endnotes

Endnotes
1. http://en.wikipedia.org/wiki/Teletype_Model_33

Get a higher mark


on your course
assignment!
Get feedback & advice from experts in your subject
area. Find out how to improve the quality of your work!

Get Started

Go to www.helpmyassignment.co.uk for more info

227 Click on the ad to read more

You might also like