Introduction To Programmingupdate 2024 5
Introduction To Programmingupdate 2024 5
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
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.
202
Introduction: Visual BASIC 6.0 Arrays and Tables
SYNTAX
Array Elements
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
An example using array elements is shown in Figure 10-5. BASIC automatically initializes storage
locations in arrays containing numeric values to zero.
cost
0 0 0 0 0
1 2 3 4 5
cost
1 2 3 4 5
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
204
Introduction: Visual BASIC 6.0 Arrays and Tables
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.
205
Introduction: Visual BASIC 6.0 Arrays and Tables
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.)
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
Input #n, N
For I = 1 To N
Input #n, dataValue(I)
Next I
Close #n
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
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.
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.
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
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.
209
Introduction: Visual BASIC 6.0 Arrays and Tables
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.
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)
elements(J) = 18
elements(K) = 9
elements(J) = 9
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.
211
Introduction: Visual BASIC 6.0 Arrays and Tables
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”))
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.
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.
The code that actually carries out the sorting is shown in Figure 10-14.
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
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.
214
Introduction: Visual BASIC 6.0 Arrays and Tables
Brackets
1 2 3 4 5
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.
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
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
216
Introduction: Visual BASIC 6.0 Arrays and Tables
- ste
the of th + -c + in + + ity
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.
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%.
218
Introduction: Visual BASIC 6.0 Arrays and Tables
End If
Rem Draw the sector
F Circle (160, 100), radius,,-startangle,-stopangle
Next I
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.
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.
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
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
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
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).
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
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.
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
224
Introduction: Visual BASIC 6.0 Index
225
Introduction: Visual BASIC 6.0 Index
226
Introduction: Visual BASIC 6.0 Endnotes
Endnotes
1. http://en.wikipedia.org/wiki/Teletype_Model_33
Get Started