In parallel arrays, corresponding elements in each array must have the same __________.
10/11/2020Client: papadok01Deadline: 3 days
7 Arrays: Lists and Tables
Although the value of a variable may change during execution of a program, in all our programs so far, a single value has been associated with each variable name at any given time. In this chapter, we will discuss the concept of an array—a collection of variables of the same type and referenced by the same name. We will discuss one-dimensional arrays (lists) and two-dimensional arrays (tables). You will learn how to set up and use arrays to accomplish various tasks.
After reading this chapter, you will be able to do the following:
· Declare and use one-dimensional arrays
· Manipulate parallel arrays
· Understand the relationship in programming between databases and parallel arrays
· Represent character strings as arrays
· Use the Length_Of() function to validate data in character arrays
· Declare and use two-dimensional arrays
· Combine one- and two-dimensional parallel arrays in a program
In the Everyday World Organize It with Lists and Tables
Chances are that you frequently use lists in your daily life. The following is a common example:
Shopping List
1. Milk
2. Bread
3. Eggs
4. Butter
Or if you’ve ever done a home improvement project, you might have developed a list such as the following:
Tools Required List
1. Hammer
2. Saw
3. Screwdriver
If you write individual items on separate random pieces of paper, you might get them confused and end up going to the grocery store for a saw. By presenting a convenient method of organizing and separating your data, a list prevents this from happening.
Sometimes a single list isn’t powerful enough for a given purpose. In this case, we use a table—a collection of related lists—such as the following:
Phone Book
· A. Name List B. Address List C. Phone List
· 1. Ellen Cole 1. 341 Totem Dr. 1. 212-555-2368
· 2. Kim Lee 2. 96 Elm Dr. 2. 212-555-0982
· 3. Jose Rios 3. 1412 Main St. 3. 212-555-1212
Notice that this table contains three separate (vertical) lists that are all related horizontally. For example, to call someone you would scan down the Name List for the appropriate name, then look across that line to the Phone List to find the corresponding phone number. Could anything be more convenient? Thanks to a little organization and structure; you can easily find what you’re looking for, even if the individual lists are hundreds of items long.
Everyone from farmers (weather tables) to accountants (ledgers) to sports fans (player statistics) uses lists and tables. If you use a spreadsheet program, you’re using an electronic table and if you write a computer program with a lot of data that “goes together,” you might organize it as a list or a table called anarray. Often, programs that use data from databases store that data in arrays in order to manipulate and process it.
7.1 One-Dimensional Arrays
A one-dimensional array is a list of related data of the same type (for example, integers or strings) referred to by a single variable name with an index number to identify each item. In this section, we will discuss how to set up and manipulate these arrays, and we will present several advantages of their use.
Array Basics
Since an array stores many data values under the same variable name, we must have some way to refer to the individual elements contained within it. Eachelement is an item in the array and has its own value. To indicate a particular element, programming languages follow the array name by an index numberenclosed in parentheses or brackets. For example, if the name of an array is Month and the index number is 3, the corresponding array element might be indicated by Month[3] .
The name of the array is similar to the name of a variable. For example, we might have an array called Scores that contains the final exam scores for a certain class of 25 students. Therefore, the array would have 25 scores. Each score is an element, and the array must indicate which particular element the program refers to at any time. This is done by using the index number. The first element of an array in most programming languages is referred to with the index number 0, although some may use 1 as the first index value. An array with 25 elements will have index numbers that range from 0 to 24. The first index value is a significant fact to keep in mind, especially when you manipulate arrays with loops. In our pseudocode, we follow the more common practice of starting array indexes with 0.
An individual element of an array is referred to by writing the array name followed by its index number surrounded by brackets. For example, since the first element of an array has index number 0, the first element of the array Scores would be referred to as Scores[0], and in that same array the second element is Scores[1]and the third is Scores[2]. We read these as "Scores sub 0", "Scores sub 1", and "Scores sub 2". Here, 0, 1, and 2 are called the subscripts—or index numbers—of the array elements.
An array element such as Scores[2] is treated by the program as a single (or simple) variable and may be used in input, assignment, and output statements in the usual way. Thus, to display the value of the third student’s final exam score, we use the following statement:
Write Scores[2]
Example 7.1 shows how to enter elements in an array.
Example 7.1 Entering Elements in an Array
If we wanted to input the final exam scores of a class of 25 students using an array named Scores, which has 25 elements, we could use a loop as follows:
For (K = 0; K < 25; K++)
Write "Enter score: "
Input Scores[K]
End For
What Happened?
· On the first pass through the loop, the input prompt is displayed ("Enter score: ") and the Input statement pauses execution, allowing the user to enter the first test score. Because K = 0, this value is then assigned to the first element of the array Scores, which is Scores[0].
· On the second pass through the loop, K = 1 and the next value input is assigned to Scores[1], the second element of Scores.
· On the third pass through the loop, the value input is assigned to Scores[2].
· Because this loop began with K = 0, we only need to go to K = 24 to complete all 25 passes through the loop and load all 25 values.
After 25 passes through this little loop, all the scores have been entered. This is certainly a more efficient way to write code than to type 25 Write and Inputstatements for 25 different variables! We will see that using arrays not only makes it much easier to load large amounts of data but also makes manipulating that data easier and more efficient.
Declaring Arrays
Arrays are stored in a computer’s memory in a sequence of consecutive storage locations. As you know, when you declare a variable the computer sets aside a small amount of memory to store the value of that variable. The data type of the variable, the name of the variable, and the value of the variable are one little package and that package is stored in a small amount of memory. When you create an array, you tell the computer what the data type is and how many elements the array will contain. Then a space in the computer’s memory is set aside for that array. If an array has five elements, the computer will set aside space with five equal parts, one part for each element of the array. Therefore, each element of the array has the same sized space in computer memory, the same array name, and the same data type. And all the elements are stored in consecutive locations in memory. The index (or subscript) number of the element sets it apart from the other members in the array.
Declaring Arrays in C++, Visual Basic, and JavaScript
While not always necessary, it is a good idea to inform the program, prior to the first use of an array, how many storage locations to set aside (or allocate) for that array. The array declaration statement can include the array name and the size of the memory space needed for that array. In program code, this is done by declaring the array in a statement at the beginning of the program or program module in which it is used. It is also possible to declare arrays without specifying the size, and this is used in some cases where the programmer may want the size of the array to be open ended. The declaration statement varies from language to language. The following shows how an array named Age, consisting of a maximum of six integer values, would be declared in three popular languages:
· In C++, the following statement:
int Age[6];
allocates six locations referred to as Age[0], Age[1], . . . , Age[5].
· In Visual Basic, the following statement:
Dim Age(6) As Integer
allocates six locations referred to as Age(0), Age(1), . . . , Age(5).
· In JavaScript, the following statement:
var Age = new Array(6);
allocates six locations referred to as Age[0], Age[1], . . . , Age[5].
In JavaScript the data type of the array will be determined when its elements are assigned values. However, all the elements of a JavaScript array must still be of the same data type.
Notice that the arrays begin with the subscript 0, and therefore, end with a subscript that is one less than the number of elements in the array.
In this book , for an array of integers, we will use the following pseudocode:
Declare Age[6] As Integer
to allocate six locations referred to as Age[0], Age[1], . . . , Age[5]. In memory, this array would occupy six consecutive storage locations, and assuming that the elements have been assigned the values 5, 10, 15, 20, 25, and 30, the array can be pictured as follows:
Address
Age[0]
Age[1]
Age[2]
Age[3]
Age[4]
Age[5]
Contents
5
10
15
20
25
30
It would have been possible to create six integer variables with the values 5, 10, 15, 20, 25, and 30. We could have named them Age5, Age10, Age15, and so forth. But there are many advantages associated with using arrays. Arrays make it easy to manipulate many variables at a time, using only a few lines of code. Example 7.2 shows the declaration and use of an array.
Example 7.2 When It Rains, It Pours, So Use an Array 1
1 Before attempting to implement the examples in this chapter with RAPTOR, be sure to read the information in the Running With RAPTOR section ( Section 7.6 ) on how RAPTOR creates and initializes arrays.
This program uses arrays to find the average monthly rainfall in Sunshine City for the year 2014, after the user has entered the rainfall for each month. First the program computes the average of the monthly rainfall for a year and then displays a list of the months, identified by number (January is month 1, February ismonth 2, and so forth), each month’s rainfall, and the year’s average monthly rainfall. In the program, we will show all the variable declarations needed, not just those for the arrays.
1 Declare Rain[12] As Float
2 Declare Sum As Float
3 Declare Average As Float
4 Declare K As Integer
5 Set Sum = 0
6 For (K = 0; K < 12; K++)
7 Write "Enter rainfall for month " + (K + 1)
8 Input Rain[K]
9 Set Sum = Sum + Rain[K]
10 End For
11 Set Average = Sum/12
12 For (K = 0; K < 12; K++)
13 Write "Rainfall for month " + (K + 1) + " is " + Rain[K]
14 End For
15 Write "The average monthly rainfall is " + Average
What Happened?
· Line 1 declares an array named Rain, which will consist of 12 elements of type Float.
· Lines 2 and 3 declare two floating point variables, Sum and Average. The initial value of Sum is set to 0 on line 5.
· Line 4 declares one integer variable, K. This variable will serve as a counter and will also identify each month when we write the display later.
· Lines 6–10 include the first For loop, where the user inputs the 12 rainfall figures (one for each month) into the array Rain. The loop also totals the value of the rainfall amounts for 12 months. At this point, note the following:
· The variable K has been initialized to 0 and is set to count to 11. This will result in 12 passes through the loop, which is what we need to load values for 12 months in a year. Since we want to associate each element of the Rain array with its corresponding value of K, we begin the loop with K = 0.
· However, the first month of the year is month 1, which is why the Write statement on line 7 asks the user to "Enter rainfall for month " + (K + 1). On the first pass, the Write statement asks for month 1 and on the 12th pass, the Write statement asks for month 12.
· Line 8 gets the input and stores the value. On the first pass, the user inputs a value for Month 1 since K + 1 = 1 and the value is stored in Rain[0] since K= 0. On the next pass, the user inputs a value for month 2 since K + 1 is now 2, but the value is stored in the second element of the Rain array, which isRain[K] or Rain[1]. On the last pass, the user enters a value for month 12, which is stored in Rain[11].
· Line 11 computes the average value of monthly rainfall amounts for the whole year.
· At this point, the computer has stored rainfall amounts as 12 variables, but all the variables are elements of the array named Rain. The computer also knows the average of the yearly rainfall. All that is left is to tell us the results.
· The second For loop on lines 12–14 displays the month (K + 1) and the amount of rainfall for that month, which was stored in Rain[K] on line 8. This line is pretty important; when we say Write Rain[K], it’s the same as saying Write the value stored in element K of the Rain array.
· Line 15 writes the average of the rainfall for all the months.
If you need to be further convinced about the advantages of using arrays to manipulate a large amount of related data, try to rewrite the pseudocode shown in Example 7.2 without an array. Instead of an array named Rain, declare 12 variables (January, February, March, April, May, June,July, August, September, October, November, and December) for the values of each month’s rainfall amounts. Then rewrite the pseudocode to display each month, its rainfall amount, and the average for the year.
In Example 7.2 , the variable we used as a counter to load the array and to identify the number of the month we were referring to at any time wasK. Initially, we set the value of K to 0, which meant that there were certain conditions that had to be met. We could not refer to the month as simplyK. Instead we had to use K + 1 since there is no month 0. We also were required to set the test condition so that the loop ends when K = 11 to ensure 12 passes. However, we could also have written this program segment with the initial value of K = 1. If you rewrite this pseudocode with K = 1, what changes will you need to make so that the program does the exact same thing as shown in Example 7.2 ? This is the first Self Check question of this section.
The following program segments show how C++, Java, and JavaScript code is implemented to load the Rain array, display its contents, and calculate and display the average of all entries. For clarity, in all code samples the variable names have been kept exactly the same as the pseudocode.
Before we move on we will use Example 7.2 to illustrate how the monthly rainfall pseudocode would look in three programming languages.
The subscript or index value of an array element can be defined as a number, a variable, or any expression that evaluates to an integer. For example, if an array isnamed Food and a variable named Num has the value of 5, all of the following will assign "cake" to the 6th element of Food:
16 cout << "Rainfall for month " << (K + 1) << " is " ↵ << Rain[K] << end1;
17 }
18 cout << "The average monthly rainfall is " << Average << end1;
19 return 0;
20 }
When It Rains . . . with Java
The Java code for Example 7.2 is as follows:
1 public static void main(String args[])
2 {
3 float Sum; float Average;
4 Rain[] = new float[12];
5 int K;
6 Scanner scanner = new Scanner(System.in);
7 Sum = 0; Average = 0;
8 for (K = 0; K < 12; K++)
9 {
10 System.out.println("Enter rainfall for month" + (K + 1);
11 Rain[K] = scanner.nextFloat();
12 Sum = (Sum + Rain[K]);
13 }
14 Average = Sum/12;
15 for (K = 0; K < 12; K++)
16 {
17 System.out.println("Rainfall for month" + (K + 1) + ↵ " is " + Rain[K]);
18 }
19 System.out.println("The average monthly rainfall is " ↵ + Average);
20 }
When It Rains . . . with JavaScript
The JavaScript code for Example 7.2 is as follows:
1
2
Rainfall
3
4 function raining()
5 {
6 var Sum = 0; var Average = 0; var K;
7 var Rain = new Array(12);
8 for (K = 0; K < 12; K++)
9 {
10 Rain[K] = parseFloat(prompt("Enter rainfall for month "));
11 Sum = Sum + Rain[K];
12 }
13 Average = Sum/12;
14 for (K = 0; K < 12; K++)
15 {
16 document.write("Rainfall for month " + (K + 1) + " is " + Rain[K] + " ");
17 }
18 document.write("The average monthly rainfall is " + Average);
19 }
20
21
22
23
There are a few noteworthy points:
· Most of the syntax for the actual logic of the program is identical for all the languages. The main differences are in how the languages handle starting a program and how they retrieve and display data. In C++, the statement int main() begins the program, while in Java, the program begins with public static void main(String args[]), and in JavaScript the main function, called raining() in this example, is accessed from a button on the web page (see line 22).
· In C++, the cout and cin statements allow for input and output. In Java, an object, called a scanner object is created. It allows input to be placed into a buffer. The item in parentheses (in this case, System.in) tells the computer where the input is coming from (the keyboard in this case). For example:
System.out.println("Enter rainfall for month" + (K + 1));
tells the computer to output what is inside the parentheses. The use of println does the same thing as endl in C++—it tells the computer to move to the next line after executing this line of code. Then the line:
Rain[K] = scanner.nextFloat();
tells the computer to look at the scanner object, get the next floating point data that is in the buffer and store it in Rain[K].
In JavaScript, the prompt statements get input from the user and store what the user enters in the variable or array element on the left side of the statement. In JavaScript, everything entered by a user is initially stored as text so the prompt is enclosed within the parseFloat() method. This changes the user’s input from text to floating point data. The prompt appears as a small window on a web page screen with a box for user input. Thus, the line:
Rain[K] = parseFloat(prompt("Enter rainfall for month "));
prompts the user for a value, converts the value to a number, and stores it in Rain[K]. Output is created with the document.write() statements. Whatever is inside the parentheses will be displayed on the web page. The tag is an indicator to move to the next line on the display.
Self Check for Section 7.1
For Self Check Questions 7.1 and 7.2 refer to Example 7.2 .
1. 7.1 Rewrite the pseudocode to load the array, Rain, with 12 rainfall amounts using K = 1 as the initial value of K.
2. 7.2 Rewrite the pseudocode of Example 7.2 using While loops instead of For loops.
In Self Check Questions 7.3 and 7.4, what is displayed when code corresponding to the given pseudocode is executed?
3. 7.3
4. Declare A[12] As Integer
5. Declare K As Integer
6. Set A[2] = 10
7. Set K = 1
8. While K <= 3
9. Set A[2 * K + 2] = K
10. Write A[2 * K]
11. Set K = K + 1
End While
12. 7.4 In this exercise, Letter is an array of characters and the characters that have been input are F, R, O, D, O.
13. Declare Letter[5] As Character
14. Declare J As Integer
15. For (J = 0; J <= 4; J++)
16. Input Letter[J]
17. End For
18. For (J = 0; J <= 4; J+2)
19. Write Letter[J]
End For
20. 7.5 The following program segment is supposed to find the average of the numbers input. It contains one error. Find and correct it.
21. Declare Avg[10] As Integer
22. Declare Sum, K As Integer
23. Set Sum = 0
24. For (K = 0; K <= 9; K++)
25. Input X[K]
26. Set Sum = Sum + X[K]
27. End For
Set Average = Sum/10
28. 7.6 State two advantages of using arrays instead of a collection of simple (unsubscripted) variables.
7.2 Parallel Arrays
In programming, we often use parallel arrays. These are arrays of the same size in which elements with the same subscript are related. For example, suppose we wanted to modify the program of Example 7.2 to find the average monthly rainfall and snowfall. If we store the snowfall figures for each month in an array named Snow, then Rain and Snow would be parallel arrays. For each K, Rain[K] and Snow[K] would refer to the same month so they are related data items. Example 7.3 illustrates this idea further.
Example 7.3 You’ll Be Sold on Parallel Arrays
This program segment inputs the names of salespersons and their total sales for a given month into two parallel arrays (Names and Sales) and determines which salesperson has the greatest sales (Max). Figure 7.1 shows the flowchart for this pseudocode. It’s helpful to walk through the flowchart to visualize the logic used to solve this problem. The pseudocode assumes that Max, K, and Index have been previously declared as Integer variables.
Pseudocode
1 Declare Names[100] As String
2 Declare Sales[100] As Float
3 Set Max = 0
4 Set K = 0
5 Write "Enter a salesperson's name and monthly sales."
6 Write "Enter *, 0 when done."
7 Input Names[K]
8 Input Sales[K]
9 While Names[K] != "*"
10 If Sales[K] > Max Then
11 Set Index = K
12 Set Max = Sales[Index]
13 End If
14 Set K = K + 1
15 Write "Enter name and sales (enter *, 0 when done)."
16 Input Names[K]
17 Input Sales[K]
18 End While
19 Write "Maximum sales for the month: " + Max
20 Write "Salesperson: " + Names[Index]
What Happened?
· In this program segment, we do not use a For loop to input the data because the number of salespersons may vary from run to run. Instead, we use a sentinel-controlled loop with an asterisk (*) and a 0 as the sentinels. The user indicates that there are no more salespeople to enter by entering the asterisk (*) for the name and 0 for the amount.
Figure 7.1
Flowchart for Example 7.3
· Lines 1 and 2 declare two arrays. Names is an array of String elements and Sales is an array of Floats. You may wonder why these arrays have been declared to have 100 elements each, when the program is going to allow the user to enter as many salespeople as necessary. In some programming languages, you may have to specify the size of the array. It’s better to declare an array for a larger number of elements than you plan to use. In this program segment, the maximum number of salespeople that can be entered is 100, but we assume that is plenty. If there are only 38 salespeople, the rest of the elements of the array are simply unused.
· Let’s look at what happens on lines 5–8 in more detail. Line 5 requests the input (a salesperson’s name and his/her monthly sales amount). Line 6 explains to the user how to finish entering data. Lines 7 and 8 are of some special interest. When a user enters a name and an amount, the first value entered is stored in the Names array and the second value entered is stored in the Sales array. This is very important! The information must be entered in the correct order. Imagine that the fifth entry was for a saleswoman named Josephine Jones whose sales totaled $4,283.51. If the information was entered in the wrong order,Names[4] would store 4283.51. This would not be the correct name, but a computer doesn’t care what text is entered into a string so a string of numbers would be a legitimate entry. However, when the user entered “Jones” into the Float array, Sales, at best the program would simply halt or give an error message or, worse, it would crash.
· Line 9 begins the loop to do the work of this program. It continues until the asterisk is entered.
· Line 10 checks to see if the value of the current salesperson’s monthly sales is greater than the maximum value to that point (Max). The variable Max holds the maximum value, so that as the entries are made, Max will continually change every time an entry has a larger sales amount.
· Line 11 sets the variable named Index equal to the value of K. K is just an integer. If the value in Sales[K] is greater than the Max value, we want the newMax value to be the value of whatever Sales[K] is at this point in the program. Let’s say for example, that Sales[3] is the high value at one point in the program. We need a way to associate that value with the salesperson who sold that amount. The variable Index keeps track of that. Regardless of what the value of K becomes as the program proceeds, until there is a higher value for Sales[K], the person associated with Names[Index] (in this case, Names[3]) remains the high seller.
· In line 12, if the current salesperson has sold more than whatever value was in Max, the new Max is set equal to sales amount of the current salesperson. If the current salesperson has not sold more than the value of Max, nothing changes.
· Lines 14–17 increment the counter and get another set of data. The loop continues until the user ends it by entering the two sentinel values.
· Line 18 simply ends the While loop and lines 19 and 20 display the results.
In Example 7.3 , what would happen if a salesperson had sold nothing for that month? The values entered would be the salesperson’s name for theName array and 0 for the Sales array. Would this create a problem? No, because the test condition tests only for the salesperson’s name. As long as the salesperson who sold nothing was not named "*", the program would continue.
And what would happen if the user decided to end the input by entering "*" for the Name array but 23 instead of 0 for the Sales array? Would the program end? Yes, it would because the test condition on line 9 (Names[K] != "*") would no longer be true, the While loop would not execute, and the value 23 would not be compared with other values.
You may be wondering why we ask the user to enter a 0 for the sales amount if the program segment is only interested in the salesperson’s name. When this program is coded and run, there are two inputs required for each entry. The user must enter something for the sales amount. We could just easily have specified "Enter *, −8,983 when done" on lines 6 and 15, but we picked 0 since it makes sense that a normal monthly sales figure wouldn’t be nothing. However, we have to specify some number since Sales is an array of numbers.
Avoiding Errors
There is a small problem with the program in Example 7.3 . If the user enters "*" at the first Input statement (line 7), the While loop is never entered. Then the variable Index on line 20 is undefined. Can you think of a way to rectify this problem?
One possible solution would be to initialize Index to an impossible value, like −1, before the loop begins. If the loop is entered, the value of Index is changed to K. But if the loop is never entered, Index retains its initial value. Then before the final display, a selection statement could check the value of Index. If it is still −1, the output might say something like “No names were entered." and a program crash would be avoided.
Some Advantages of Using Arrays
There are many advantages to using arrays and even more advantages to using parallel arrays. As you have already seen, arrays can reduce the number of variable names needed in a program because we can use a single array instead of a collection of simple variables to store related data. Also arrays can help create more efficient programs. Once data are entered into an array, that data can be processed many times without having to be input again.
Example 7.4 illustrates this point.
Example 7.4 Arrays Save You Time and Effort
Professor Merlin has asked you to help him. He has 100 students in his four classes but he is not sure that all of them took his last exam. He wants to average the grades for his last exam in four sections of his medieval literature course and then determine how many students scored above the average. Without arrays you would have to enter all the test scores, find their average, and then enter them again to determine how many exceed the average. But you know how to use arrays, so you won’t need to enter the input a second time. The following pseudocode does the job. We assume that the variables have been declared as given:
· Integer variables: Sum, Count1, Count2, and K
· Float variables: Score and Average
1 Declare Medieval[100] As Float
2 Set Sum = 0
3 Set Count1 = 0
4 Write "Enter a test score (or 999 to quit): "
5 Input Score
6 While Score != 999
7 Set Medieval[Count1] = Score
8 Set Count1 = Count1 + 1
9 Set Sum = Sum + Score
10 Write "Enter another score or 999 to quit: "
11 Input Score
12 End While
13 Set Average = Sum/Count1
14 Set Count2 = 0
15 Set K = 0
16 While K < Count1
17 If Medieval[K] > Average Then
18 Set Count2 = Count2 + 1
19 End If
20 Set K = K + 1
21 End While
22 Write "The average is:" + Average
23 Write "The number of scores above the average is: " + Count2
What Happened?
In the first While loop, which inputs the scores, the Count1 variable serves as a subscript for the array Medieval and also counts the number of scores input. Since we don’t know exactly how many students took the exam, we must use a sentinel-controlled loop here. However, when it’s time to determine the number of items above the average (Count2), we know the number of items that have been input. A second While loop is used (lines 16–21) with a limit value of one less than Count1 to determine the number of scores above the average.
Let’s think about this limit value for a moment. The value of Count1 on line 12, at the end of the While loop, is equal to the number of scores entered. For example, since Count1 is initialized to 0 on line 3, each time Professor Merlin enters a score for a student, Count1 has the value of 1 less than the number of students up to that time. This is done so that the value of the first score will be stored in Medieval[0]. However, Count1 is incremented on the line following the score input (line 8). Therefore, when all the scores have been entered and the While loop is exited, Count1 will have the same value as the number of scores that have been entered. For example, if the Professor has 23 students in a class, he will store those students’ scores in Medieval[0] through Medieval[22]but, on exiting the While loop, Count1 will equal 23.
The While loop that begins on line 16 needs to compare each score (each element of the Medieval array) with the value of Average. Therefore, if there are 23 scores entered in Medieval[0] through Medieval[22], the loop must make 23 passes. The counter for this loop, K, begins at 0 and, since it increments by 1for each pass, by the time K has reached 22, it will have completed 23 passes. This is why we set the limit condition of this loop on line 16 to K < Count1.
Another benefit of using arrays is that they help create programs that can be used with greater generality. If we use 30 simple variables to hold the values for 30 test scores, we can only have 30 test scores. If five students register late for a class and we need variables for 35 students, we have to declare five more variables. However, because we do not have to use all the elements that were allocated to an array when it was declared, arrays give us more flexibility, as shown in Example 7.5 . We could initialize an array for scores with space for 50 elements, even if we only use 30, or later in the semester, use 35. The unused spaces in the computer’s memory are set aside for a value, if one is entered.
Example 7.5 Arrays Make Programming Easy and Concise
Professor Merlin received a list of all his students from the head of his department. The names are listed in alphabetical order from A to Z. But Professor Merlin is not a forward-thinking professor. He likes his student class list to appear in reverse alphabetical order from Z to A. He asks you to write a program to allow him to input a list of names and display them in reverse alphabetical order. This is easy to do using arrays, even if the number of names to be input is unknown at the time the program is written.
1 Declare Names[100] As String
2 Set Count = 0
3 Write "Enter a name. (Enter * to quit.)"
4 Input TempName
5 While TempName != "*"
6 Set Names[Count] = TempName
7 Set Count = Count + 1
8 Write "Enter a name. (Enter * to quit.)"
9 Input TempName
10 End While
11 Set K = Count − 1
12 While K >= 0
13 Write Names[K]
14 Set K − K − 1
15 End While
What Happened?
This program segment inputs the list of names into the array Names and then displays the elements of that array in reverse order by “stepping backward” through a While loop whose control variable (K) is also the array subscript. The purpose of the variable TempName is to hold the string entered by the user temporarily. If that string is really a name and not the sentinel value "*", the first While loop is entered and the string is assigned to the next array element.
Note that when the first While loop ends, the value of Count is one greater than the highest subscript of the Names array. This is why we begin the secondWhile loop with the new counter, K, set equal to the value of Count − 1.
A Word About Databases
Nowadays, virtually all companies and organizations store enormous amounts of data in databases. Databases consist of many tables that are linked in many ways. As we have seen, a table can contain lists of related data; in other words, a table is a group of parallel lists. The information in the tables can be retrieved and processed for a large variety of purposes.
How Databases May Be Used
Imagine a database used by a company that provides and sells online computer games. The company might have one or more tables that store information about people who play each game. If this imaginary company offers fifteen games—say, five word games, five adventure games, and five brain teaser games—the owners might want to do some market research. While each table relating to one game might include players’ information, such as the player’s name, username, age, contact information, dates played, scores, and so on, the market research might only be interested in some of this data. The owners might want to identify which age groups gravitate to which types of games or if scores are a factor in deciding which players keep returning to a certain game. By performing what is called a query, the owner can get this information quickly from the database.
Using the same tables in the database, the company’s market research team can compile many types of information. Queries can discover which games are played most often on weekends, during daytime hours, how many players of what ages, gender, or even location are most likely to play which types of games and much more.
The company can also, using the information in the database, offer users of the site options to view statistics of other players or even find ways to get players to work together.
How Do Arrays Fit In?
The data retrieved from databases is processed and displayed through computer programs. When these programs are written, often the required information from the tables is temporarily stored in parallel arrays. It is manipulated, processed, and the results are output not directly from the database but from the arrays in the programs that are written by programmers. Therefore, while it is important to understand how to get and use information to load arrays directly from a user, understanding how to use arrays has a much more far-reaching purpose. Working with arrays is central to virtually all computer applications in today’s world.
Self Check for Section 7.2
1. 7.7 Write a program segment that inputs 20 numbers in increasing order and displays them in reverse order.
2. 7.8 Redo Example 7.2 so that a user will enter values for both snowfall and rainfall for each month using parallel arrays, Rain and Snow.
3. 7.9 Add to the program you created in Self Check Question 7.8 so that the display shows corresponding values for snowfall and rainfall for each month. Before displaying the averages for snowfall and rainfall, each output line should look like this:
4. 7.10 Give two examples of situations where parallel arrays would be useful.
5. 7.11 True or False: An array of names and an array of numbers cannot be parallel because they are of different data types.
6. 7.12 Imagine you are starting your own small business selling widgets that you create in your home workshop. You want to keep track of your customers in a database. List the information you might store in a table about customers.
7. 7.13 Add to the imaginary database you created in Self Check Question 7.12 by listing information you might want to store in a table about your inventory.
7.3 Strings as Arrays of Characters
In the first section of this chapter, we described one-dimensional arrays and some ways to use them. In this section, we will discuss how arrays are related to the topic of character strings.
In Chapter 1 , we introduced character strings (or more simply, strings) as one of the basic data types. Some programming languages do not contain a string data type. In those languages, strings are implemented as arrays whose elements are characters. Even in programming languages that contain this data type, strings can be formed as arrays of characters. In this section, we will consider strings from this point of view. If you have been using the RAPTOR sections of this text you will recall how we used the RAPTOR indexing property to access specified characters in a string of text. When indexing is used, a string is processed as an array of characters in the manner that will be described in this section.
When defining a string as an array of characters in our pseudocode, we will always indicate the data type in the Declare statement. This practice is normally required when writing actual code. For example, the following statements
Declare FirstName[15] As Character
Declare LastName[20] As Character
define the variables FirstName and LastName to be strings of at most 15 and 20 characters, respectively.
Concatenation Revisited
Whether we consider strings as a built-in data type or as arrays of characters, we can perform certain basic operations on them, as shown in Example 7.6 .
Example 7.6 Stringing Arrays Together
This program segment inputs two strings from the user, concatenates them, and displays the result. You will recall that concatenation means to join two items, and the + symbol is used to perform the concatenation operation.
Declare String1[25] As Character
Declare String2[25] As Character
Declare String3[50] As Character
Write "Enter two character strings. "
Input String1
Input String2
Set String3 = String1 + String2
Write String3
In this pseudocode, notice that String1, String2, and String3 are defined as arrays of characters, but when they are used in the program, the array brackets do not appear. For example, we write
Input String1
Input String2
rather than
Input String1[25]
Input String2[25]
This usage is typical of actual programming languages and also conforms to our previous way of referencing strings when they were considered as a built-in data type.
After the two strings have been input, the statement
Set String3 = String1 + String2
concatenates them and the Write statement displays the result. If code corresponding to this pseudocode is run and the user enters the strings "Part" and "Time" for String1 and String2, the program’s output would be as follows:
PartTime
Concatenation versus Addition
The use of the concatenation operator in the following line of Example 7.6
Set String3 = String1 + String2
merits a short comment at this point.
If, for example, a person had three Integer variables as follows:
Var1 = 10, Var2 = 15, Var3 = 0
the statement:
Set Var3 = Var1 + Var2
would result in Var3 = 25.
However, if Var1, Var2, and Var3 were String variables with values as follows:
Var1 = "10", Var2 = "15", Var3 = "0"
the statement
Set Var3 = Var1 + Var2
would result in Var3 = "1015"
In our pseudocode, as well as in most programming languages that use the same symbol for concatenation as for addition, it is the data type declaration that tells the computer which operation (addition or concatenation) to perform.
In a language like JavaScript (or RAPTOR), you must use parentheses to ensure that the computer knows when the + sign indicates addition. The following JavaScript code snippet will demonstrate this:
function concatenation()
{
var Var1 = 24;
var Var2 = 12;
document.write("Var1 concatenated with Var2 is: " + Var1 + ↵ Var2 + " ");
document.write("Var1 added to Var2 is: " + (Var1 + Var2));
}
The output from this program would be:
Var1 concatenated with Var2 is: 2412
Var1 added to Var2 is: 36
String Length versus Array Size
The length of a string is the number of characters it contains. For example, the array String3 of Example 7.6 is declared as an array of 50 elements, but when "PartTime" is assigned to String3, only the first eight array elements are used. Thus, the length of the string "PartTime" is 8.
In some algorithms (see Example 7.7 ), it is useful to know the length of a string that has been assigned to a given array of characters. For this purpose, programming languages contain a Length_Of() function, which we will write as follows:
Length_Of(String)
We have discussed this function earlier in the text and used it in several RAPTOR programs. We will now review its characteristics and applications in the context of character arrays.
The value of the Length_Of() function is the length of the given string or string variable and may be used in a program wherever a numeric constant is valid. For example, when code corresponding to the following pseudocode is run:
Declare Str[10] As Character
Set Str = "HELLO"
Write Length_Of(Str)
the output will be the number 5 because the string "HELLO" is made up of five characters.
Recall that when an array is declared, the number specified in the declaration statement determines the number of storage locations in the computer’s memory allocated to that array. If the array represents a string (an array of characters), then each storage location consists of one byte of memory. When a string is assigned to this array, the beginning elements of the array are filled with the characters that make up the string, a special symbol is placed in the next storage location, and the rest of the array elements remain unassigned. For example, a string named Str declared as an array of 8 characters and assigned the value "HELLO" can be pictured to look in memory as follows:
Address
Str[0]
Str[1]
Str[2]
Str[3]
Str[4]
Str[5]
Str[6]
Str[7]
Contents
"H"
"E"
"L"
"L"
"O"
#
Here, the symbol # represents the character that is automatically placed at the end of the assigned string. Thus, to determine the length of the string contained inStr, the computer simply counts the storage locations (bytes) associated with the variable Str until the terminator symbol, #, is reached.
Example 7.7 illustrates how the Length_Of() function can be used to validate input when that input must be within a certain range of characters.
Example 7.7 Using the Length_Of() Function To Validate Input
It is sometimes necessary to ensure that a string of text does not exceed a certain limit or is within a given range of allowable characters. The following program segment demonstrates the use of the Length_Of() function to validate that a user’s input for a username on a website is between 1 and 12 characters.
1 Declare Username[12] As Character
2 Declare Valid As Integer
3 Write "Enter your username. It must be at least 1 but ↵ no more than 12 characters:"
4 Input Username
5 Set Valid = Length_Of(Username)
6 While Valid < 1 OR Valid > 12
7 If Valid < 1 Then
8 Write "Username must contain at least one ↵ character. Please try again:"
9 Else
10 If Valid > 12 Then
11 Write "Username cannot be more than 12 ↵ characters. Please try again:"
12 End If
13 Input Username
14 Set Valid = Length_Of(Username)
15 End If
16 End While
What Happened?
The Length_Of() function finds out how many characters are in the character array, Username, and this integer is stored in Valid. Let’s discuss the logic in theWhile loop from line 6 through line 16. This loop will not be entered if Valid is a number between 1 and 12 so nothing will occur. But if Valid is either less than 1 or greater than 12, the loop will begin. If there is nothing stored in Username (i.e., Valid < 1), the If-Then statement on line 8 will execute. If this condition is not true, then Valid must be greater than 12 (or the loop would have been skipped) so line 11 will execute. Either way, a new Username is input (line 13) and its length is checked again on line 14.
She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!
Hey, I have gone through your job posting and become very much interested in working with you.I can deliver professional content as per your requirements. I am a multi-skilled person with sound proficiency in the English language for being a native writer who worked on several similar projects of content writing and can deliver quality content to tight deadlines. I am available for both online and offline writing jobs with the promise of offering an incredibly responsive and supreme level of customer service. Thanks!
Hey, I have gone through your job posting and become very much interested in working with you.I can deliver professional content as per your requirements. I am a multi-skilled person with sound proficiency in the English language for being a native writer who worked on several similar projects of content writing and can deliver quality content to tight deadlines. I am available for both online and offline writing jobs with the promise of offering an incredibly responsive and supreme level of customer service. Thanks!
Hello, I can assist you in writing attractive and compelling content on ganja and its movement globally. I will provide with valuable, informative content that you will appreciate. The content will surely hit your target audience. I will provide you with the work that will be according to the needs of the targeted audience and Google’s requirement.