Array Processin g
C++ provides many ways to access arrays. If you have programmed in other computer languages, you will find that some of C++’s array indexing techniques are unique. Arrays in the C++ language are closely linked with pointers. Chapter 26, “Pointers,” describes the many ways pointers and arrays interact. Because pointers are so powerful, and because learning about arrays provides a good foun- dation for learning about pointers, this chapter attempts to describe in detail how to reference arrays.
This chapter discusses the different types of array processing. You learn how to search an array for one or more values, find the highest and lowest values in an array, and sort an array into numerical or alphabetical order.
This chapter introduces the following concepts:
-
Searching arrays
-
Finding the highest and lowest values in arrays
-
Sorting arrays
-
Advanced subscripting with arrays
Many programmers see arrays as a turning point. Gaining an understanding of array processing makes your programs more accurate and allows for more powerful programming.
Array elements do
Searching Array s
Arrays are one of the primary means by which data is stored in C++ programs. Many types of programs lend themselves to process- ing lists (arrays) of data, such as an employee payroll program, a scientific research of several chemicals, or customer account pro- cessing. As mentioned in the previous chapter, array data usually is read from a disk file. Later chapters describe disk file processing. For now, you should understand how to manipulate arrays so you see the data exactly the way you want to see it.
Chapter 23, “Introducing Arrays,” showed how to print arrays
not always appear in the order in which they are needed.
in the same order that you entered the data. This is sometimes done, but it is not always the most appropriate method of looking at data. For instance, suppose a high school used C++ programs for its grade reports. Suppose also that the school wanted to see a list of the top 10 grade-point averages. You could not print the first 10 grade- point averages in the list of student averages because the top 10 GPAs might not (and probably will not) appear as the first 10 array elements. Because the GPAs would not be in any sequence, the program would have to sort the array into numeric order, from high
GPAs to low, or else search the array for the 10 highest GPAs.
You need a method for putting arrays in a specific order. This is called sorting an array. When you sort an array, you put that array in a specific order, such as in alphabetical or numerical order. A dictionary is in sorted order, and so is a phone book.
When you reverse the order of a sort, it is called a descending sort. For instance, if you wanted to look at a list of all employees in descending salary order, the highest-paid employees would be printed first.
Figure 24.1 shows a list of eight numbers in an array called unsor t ed . The middle list of numbers is an ascending sorted version of unsor t ed . The third list of numbers is a descending version of unsor t ed .
Figure 24.1. A list of unsorted numbers sorted into an ascending and a descending order.
Before you learn to sort, it would be helpful to learn how to search an array for a value. This is a preliminary step in learning to sort. What if one of those students received a grade change? The computer must be able to access that specific student’s grade to change it (without affecting the others). As the next section shows, programs can search for specific array elements.
You do not have to
Searching for Value s
You do not have to know any new commands to search an array for a value. Basically, the i f and f or loop statements are all you need. To search an array for a specific value, look at each element in that array, and compare it to the i f statement to see whether they match. If they do not, you keep searching down the array. If you run out of array elements before finding the value, it is not in the array.
You can perform several different kinds of searches. You might
sort an array to find its extreme values.
have to find the highest or the lowest value in a list of numbers. This is informative when you have much data and want to know the extremes of the data (such as the highest and lowest sales region in your division). You also can search an array to see whether it contains a matching value. For example, you can see whether an item is already in an inventory by searching a part number array for a match.
The following programs illustrate some of these array- searching techniques.
Examples
- To
find the highest number in an array, compare each element with the first one. If you find a higher value, it becomes the basis for the rest of the array. Continue until you reach the end of the array and you will have the highest value, as the following program shows.
Identify the program and include the I/O header file. You want to find the highest value in an array, so define the array size as a constant, then initialize the array.
Loop through the array, comparing each element to the highest value. If an element is higher than the highest value saved, store the element as the new high value. Print the highest value found in the array.
/ / Fil ename: C24HI GH. CPP
/ / Fi nds t he hi ghest val ue i n t he arr ay. #i ncl ude <i ost r eam. h>
const i nt SI ZE = 15; voi d mai n()
{
/ / Put s some number s i n t he arr ay.
i nt ar a[ SI ZE] ={ 5, 2, 7, 8, 36, 4, 2, 86, 11, 43, 22, 12, 45, 6, 85} ;
i nt hi gh_val , ct r ;
hi gh_val = ar a[ 0] ; / / I ni t i ali zes wi t h f i r st
/ / arr ay el ement.
f or ( ct r =1; ct r <SI ZE; ct r ++)
{ / / St or es curr ent val ue i f i t i s
/ / t he hi gher t han t he hi ghest. i f ( ar a[ ct r ] > hi gh_val )
{ hi gh_val = ar a[ ct r ] ; }
}
cout << “ The hi ghest number i n t he li st i s “
<< hi gh_val << “ \ n” ; r et ur n;
}
The output of the program is the following:
The hi ghest number i n t he li st i s 86.
You have to save the element if and only if it is higher than the one you are comparing. Finding the smallest number in an array is just as easy, except that you determine whether each succeeding array element is less than the lowest value found so far.
- The
following example expands on the previous one by finding the highest and the lowest value. First, store the first array element in both the highest and the lowest variable to begin the search. This ensures that each element after that one is tested to see whether it is higher or lower than the first.
This example also uses the r and() function from Chapter 22, “Character, String, and Numeric Functions,” to fill the array with random values from 0 to 99 by applying the modulus operator (%) and 100 against whatever value r and() produces. The program prints the entire array before starting the search for the highest and the lowest.
/ / Fil ename: C24HI LO. CPP
/ / Fi nds t he hi ghest and t he l owest val ue i n t he arr ay. #i ncl ude <i ost r eam. h>
#i ncl ude <st dli b. h> const i nt SI ZE = 15; voi d mai n()
{
i nt ar a[ SI ZE];
i nt hi gh_val , l ow_val , ct r ;
/ / Fill s arr ay wi t h r andom number s f r om 0 t o 99. f or ( ct r =0; ct r <SI ZE; ct r ++)
{ ar a[ ct r ] = r and() % 100; }
/ / Pr i nt s t he arr ay t o t he scr een.
cout << “ Her e ar e t he “ << SI ZE << “ r andom number s:\ n” ; f or ( ct r =0; ct r <SI ZE; ct r ++)
{ cout << ar a[ ct r ] << “ \ n” ; }
cout << “ \ n\ n” ; / / Pr i nt s a bl ank li ne.
hi gh_val = ar a[ 0] ; / / I ni t i ali zes f i r st el ement t o
/ / bot h hi gh and l ow.
l ow_val = ar a[ 0];
f or ( ct r =1; ct r <SI ZE; ct r ++)
{ / / St or es curr ent val ue i f i t i s
/ / hi gher t han t he hi ghest. i f ( ar a[ ct r ] > hi gh_val )
{ hi gh_val = ar a[ ct r ] ; } i f ( ar a[ ct r ] < l ow_val )
{ l ow_val = ar a[ ct r ] ; }
}
cout << “ The hi ghest number i n t he li st i s “ << hi gh_val << “ \ n” ;
cout << “ The l owest number i n t he li st i s “ << l ow_val << “ \ n” ;
r et ur n;
}
Here is the output from this program:
Her e ar e t he 15 r andom number s:
46
30
82
90
56
17
95
15
48
26
4
58
71
79
92
The hi ghest number i n t he li st i s 95 The l owest number i n t he li st i s 4
- The next program fills an array with part numbers from an inventory.
You must use your imagination, because the inventory array normally would fill more of the array, be initialized from a disk file, and be part of a larger set of arrays that hold descriptions, quantities, costs, selling prices, and so on. For this example, assignment statements initialize the array. The important idea from this program is not the array initialization, but the method for searching the array.
/ / Fil ename: C24SERCH. CPP
/ / Sear ches a par t number arr ay f or t he i nput val ue. If
/ / t he ent er ed par t number i s not i n t he arr ay, i t i s
/ / added. I f t he par t number i s i n t he arr ay, a message
/ / i s pr i nt ed.
#i ncl ude <i ost r eam. h> const i nt MAX = 100;
voi d f ill _par t s( l ong i nt par t s[ MAX] ) ;
voi d mai n()
{
l ong i nt sear ch_par t ; / / Hol ds user r equest. l ong i nt par t s[ MAX];
i nt ct r ;
i nt num_par t s=5; / / Begi nni ng i nvent or y count.
f ill _par t s( par t s) ; / / Fill s t he f i r st f i ve el ement s. do
{
cout << “ \ n\ nPl ease t ype a par t number ... ” ; cout << “(- 9999 ends pr ogr am) “ ;
ci n >> sear ch_par t;
i f ( sear ch_par t == - 9999)
{ br eak; } / / Exi t s l oop i f user want s.
/ / Scans arr ay t o see whet her par t i s i n i nvent or y.
f or ( ct r =0; ct r <num_par t s; ct r ++) / / Checks each i t em.
{ i f ( sear ch_par t == par t s[ ct r ] ) / / I f i t i s i n
/ / i nvent or y...
{ cout << “ \ nPar t “ << sear ch_par t << “ i s al r eady i n i nvent or y” ;
br eak;
}
el se
{ i f ( ct r == ( num_par t s- 1) ) / / I f not t her e,
/ / adds i t.
{ par t s[ num_par t s] = sear ch_par t ; / / Adds t o
/ / end of arr ay.
num_par t s++;
cout << sear ch_par t <<
“ was added t o i nvent or y\ n” ;
br eak;
}
}
}
} whil e ( sear ch_par t ! = - 9999) ; / / Loops unt il user
/ / si gnal s end.
r et ur n;
}
voi d f ill _par t s( l ong i nt par t s[ MAX] )
{
/ / Assi gns f i ve par t number s t o arr ay f or t est i ng. par t s[ 0] = 12345;
par t s[ 1] = 24724; par t s[ 2] = 54154; par t s[ 3] = 73496; par t s[ 4] = 83925; r et ur n;
}
Here is the output from this program:
Pl ease t ype a par t number ... (- 9999 ends pr ogr am) 34234 34234 was added t o i nvent or y
Pl ease t ype a par t number ... (- 9999 ends pr ogr am) 83925 Par t 83925 i s al r eady i n i nvent or y
Pl ease t ype a par t number ... (- 9999 ends pr ogr am) 52786 52786 was added t o i nvent or y
Pl ease t ype a par t number ... (- 9999 ends pr ogr am) - 9999
Sorting Array s
There are many times when you must sort one or more arrays. Suppose you were to take a list of numbers, write each number on a separate piece of paper, and throw all the pieces of paper into the air. The steps you take—shuffling and changing the order of the
pieces of paper and trying to put them in order—are similar to what your computer goes through to sort numbers or character data.
Because sorting arrays requires exchanging values of elements back and forth, it helps if you first learn the technique for swapping variables. Suppose you had two variables named scor e1 and scor e2 . What if you wanted to reverse their values (putting scor e2 into the scor e1 variable, and vice versa)? You could not do this:
scor e1 = scor e2; / / Does not swap t he t wo val ues. scor e2 = scor e1;
Why doesn’t this work? In the first line, the value of scor e1 is replaced with scor e2 ’s value. When the first line finishes, both scor e1 and scor e2 contain the same value. Therefore, the second line cannot work as desired.
To swap two variables, you have to use a third variable to hold the intermediate result. (This is the only function of this third variable.) For instance, to swap scor e1 and scor e2 , use a third variable (called hol d_scor e in this code), as in
The lowest values in a list “float” to the top with the bubble sort algorithm.
hol d_scor e = scor e1; / / These t hr ee li nes pr oper l y scor e1 = scor e2; / / swap scor e1 and scor e2. scor e2 = hol d_scor e;
This exchanges the values in the two variables.
There are several different ways to sort arrays. These methods include the bubble sort, the quicksort, and the shell sort. The basic goal of each method is to compare each array element to another array element and swap them if the higher value is less than the other.
The theory behind these sorts is beyond the scope of this book, however, the bubble sort is one of the easiest to understand. Values in the array are compared to each other, a pair at a time, and swapped if they are not in back-to-back order. The lowest value eventually “floats” to the top of the array, like a bubble in a glass of soda.
Figure 24.2 shows a list of numbers before, during, and after a bubble sort. The bubble sort steps through the array and compares pairs of numbers to determine whether they have to be swapped. Several passes might have to be made through the array before it is
finally sorted (no more passes are needed). Other types of sorts improve on the bubble sort. The bubble sort procedure is easy to program, but it is slower compared to many of the other methods.
Figure 24.2. Sorting a list of numbers using the bubble sort.
The following programs show the bubble sort in action.
Examples
- The
following program assigns 10 random numbers between 0 and 99 to an array, then sorts the array. A nested f or loop is perfect for sorting numbers in the array (as shown in the
sor t _arr ay() function). Nested f or loops provide a nice mech- anism for working on pairs of values, swapping them if needed. As the outside loop counts down the list, referenc- ing each element, the inside loop compares each of the remaining values to those array elements.
/ / Fil ename: C24SORT1. CPP
/ / Sor t s and pr i nt s a li st of number s. const i nt MAX = 10;
#i ncl ude <i ost r eam. h> #i ncl ude <st dli b. h>
voi d f ill _arr ay( i nt ar a[ MAX] ) ; voi d pr i nt _arr ay( i nt ar a[ MAX] ) ; voi d sor t _arr ay( i nt ar a[ MAX] ) ;
voi d mai n()
{
i nt ar a[ MAX];
f ill _arr ay( ar a) ; / / Put s r andom number s i n t he arr ay. cout << “ Her e ar e t he unsor t ed number s:\ n” ;
pr i nt _arr ay( ar a) ; / / Pr i nt s t he unsor t ed arr ay. sor t _arr ay( ar a) ; / / Sor t s t he arr ay.
cout << “ \ n\ nHer e ar e t he sor t ed number s:\ n” ;
pr i nt _arr ay( ar a) ; / / Pr i nt s t he newl y sor t ed arr ay. r et ur n;
}
voi d f ill _arr ay( i nt ar a[ MAX] )
{
/ / Put s r andom number s i n t he arr ay. i nt ct r ;
f or ( ct r =0; ct r <MAX; ct r ++)
{ ar a[ ct r ] = (r and() % 100) ; } / / For ces number t o
/ / 0- 99 r ange.
r et ur n;
}
voi d pr i nt _arr ay( i nt ar a[ MAX] )
{
/ / Pr i nt s t he arr ay. i nt ct r ;
f or ( ct r =0; ct r <MAX; ct r ++)
{ cout << ar a[ ct r ] << “ \ n” ; } r et ur n;
}
voi d sor t _arr ay( i nt ar a[ MAX] )
{
/ / Sor t s t he arr ay.
i nt t emp; / / Tempor ar y var i abl e t o swap wi t h i nt ct r 1, ct r 2; / / Need t wo l oop count er s t o
/ / swap pai r s of number s. f or ( ct r 1=0; ct r 1<( MAX- 1) ; ct r 1++)
{ f or ( ct r 2=( ct r 1+1) ; ct r 2<MAX; ct r 2++) / / Test pai r s.
{ i f ( ar a[ ct r 1] > ar a[ ct r 2] ) / / Swap i f t hi s
{ t emp = ar a[ ct r 1] ; / / pai r i s not i n or der . ar a[ ct r 1] = ar a[ ct r 2];
ar a[ ct r 2] = t emp; / / “ Fl oat ” t he l owest
/ / t o t he hi ghest.
}
}
}
r et ur n;
}
The output from this program appears next. If any two ran- domly generated numbers were the same, the bubble sort would work properly, placing them next to each other in the list.
Her e ar e t he unsor t ed number s: 46
30
82
90
56
17
95
15
48
26
To produce a descending sort, use the less-than<() logical operator when swapping array elements.
Her e ar e t he sor t ed number s:
15
17
26
30
46
48
56
82
90
95
- The following program is just like the previous one, except it
prints the list of numbers in descending order.
A descending sort is as easy to write as an ascending sort. With the ascending sort (from low to high values), you compare pairs of values, testing to see whether the first is greater than the second. With a descending sort, you test to see whether the first is less than the second one.
/ / Fil ename: C24SORT2. CPP
/ / Sor t s and pr i nt s a li st of number s i n r ever se
/ / and descendi ng or der . const i nt MAX = 10;
#i ncl ude <i ost r eam. h> #i ncl ude <st dli b. h>
voi d f ill _arr ay( i nt ar a[ MAX] ) ;
voi d pr i nt _arr ay( i nt ar a[ MAX] ) ; voi d sor t _arr ay( i nt ar a[ MAX] ) ;
voi d mai n()
{
i nt ar a[ MAX];
f ill _arr ay( ar a) ; / / Put s r andom number s i n t he arr ay. cout << “ Her e ar e t he unsor t ed number s:\ n” ;
pr i nt _arr ay( ar a) ; / / Pr i nt s t he unsor t ed arr ay.
sor t _arr ay( ar a) ; / / Sor t s t he arr ay.
cout << “ \ n\ nHer e ar e t he sor t ed number s:\ n” ;
pr i nt _arr ay( ar a) ; / / Pr i nt s t he newl y sor t ed arr ay. r et ur n;
}
voi d f ill _arr ay( i nt ar a[ MAX] )
{
/ / Put s r andom number s i n t he arr ay. i nt ct r ;
f or ( ct r =0; ct r <MAX; ct r ++)
{ ar a[ ct r ] = (r and() % 100) ; } / / For ces number
/ / t o 0- 99 r ange.
r et ur n;
}
voi d pr i nt _arr ay( i nt ar a[ MAX] )
{
/ / Pr i nt s t he arr ay i nt ct r ;
f or ( ct r =0; ct r <MAX; ct r ++)
{ cout << ar a[ ct r ] << “ \ n” ; } r et ur n;
}
voi d sor t _arr ay( i nt ar a[ MAX] )
{
/ / Sor t s t he arr ay.
i nt t emp; / / Tempor ar y var i abl e t o swap wi t h.
i nt ct r 1, ct r 2; / / Need t wo l oop count er s
/ / t o swap pai r s of number s. f or ( ct r 1=0; ct r 1<( MAX- 1) ; ct r 1++)
{ f or ( ct r 2=( ct r 1+1) ; ct r 2<MAX; ct r 2++) / / Test pai r s
/ / Not i ce t he di ff er ence i n descendi ng ( her e)
/ / and ascendi ng.
{ i f ( ar a[ ct r 1] < ar a[ ct r 2] ) / / Swap i f t hi s
{ t emp = ar a[ ct r 1] ; / / pai r i s not i n or der . ar a[ ct r 1] = ar a[ ct r 2];
ar a[ ct r 2] = t emp; / / “ Fl oat ” t he l owest
/ / t o t he hi ghest.
}
}
}
r et ur n;
}
You can sort character arrays just as easily as you sort numeric arrays. C++ uses the ASCII character set for its sorting comparisons. If you look at the ASCII table in Appendix C, you will see that numbers sort before letters and that uppercase letters sort before lowercase letters.
Advanced Referencin g of Array s
The array notation you have seen so far is common in computer programming languages. Most languages use subscripts inside brackets (or parentheses) to refer to individual array elements. For instance, you know the following array references describe the first
and fifth element of the array called sal es (remember that the starting subscript is always 0):
An array name is the address of the starting element of the array.
sal es[ 0]
sal es[ 4]
C++ provides another approach to referencing arrays. Even though the title of this section includes the word “advanced,” this array-referencing method is not difficult. It is very different, how- ever, especially if you are familiar with another programming language’s approach.
There is nothing wrong with referring to array elements in the manner you have seen so far, however, the second approach, unique to C and C++, will be helpful when you learn about pointers in upcoming chapters. Actually, C++ programmers who have pro- grammed for several years rarely use the subscript notation you have seen.
In C++, an array’s name is not just a label for you to use in programs. To C++, the array name is the actual address where the first element begins in memory. Suppose you define an array called amount s with the following statement:
i nt amount s[ 6] = { 4, 1, 3, 7, 9, 2} ;
Figure 24.3 shows how this array is stored in memory. The figure shows the array beginning at address 405,332. (The actual addresses of variables are determined by the computer when you load and run your compiled program.) Notice that the name of the array, amount s , is located somewhere in memory and contains the address of amount s[ 0] , or 405,332.
You can refer to an array by its regular subscript notation, or by modifying the address of the array. The following refer to the third element of amount s :
amount s[ 3] and ( amount s + 3) [ 0]
Because C++ considers the array name to be an address in memory that contains the location of the first array element, nothing keeps you from using a different address as the starting address and referencing from there. Taking this one step further, each of the following also refers to the third element of amount s :
( amount s+0) [ 3] and ( amount s+2) [ 1] and ( amount s- 2) [ 5] ( 1+amount s) [ 2] and ( 3+amount s) [ 0] and ( amount s+1) [ 2]
You can print any of these array elements with cout .
Figure 24.3. The array name amount s holds the address of amount s[ 0] .
When you print strings inside character arrays, referencing the arrays by their modified addresses is more useful than with integers. Suppose you stored three strings in a single character array. You could initialize this array with the following statement:
char names[] ={ ‘ T’ , ’ e’ , ’ d’ , ’ \ 0' , ’ E’ , ’ v’ , ’ a’ , ’ \ 0' , ’ S’ , ‘ a’ , ’ m’ , ’ \ 0' } ;
Figure 24.4 shows how this array might look in memory. The array name, names, contains the address of the first element, names[ 0] (the letter T).
Figure 24.4. Storing more than one string in a single character array.
cout prints strings in arrays starting at the array’s address and continuing until it reaches the null zero.
You have yet to see a character array that holds more than one string, but C++ allows it. The problem with such an array is how you reference, and especially how you print, the second and third strings. If you were to print this array using cout :
cout << names;
C++ would print the following:
Ted
Because cout requires a starting address, you can print the three strings with the following cout s:
cout << names; / / Pr i nt s Ted cout << ( names+4) ; / / Pr i nt s Eva cout << ( names+8) ; / / Pr i nt s Sam
To test your understanding, what do the following cout s print?
cout << ( names+1) ; cout << ( names+6) ;
The first cout prints ed. The characters ed begin at ( names+1) and the cout stops printing when it reaches the null zero. The second cout prints a. Adding six to the address at names produces the address where the a is located. The “string” is only one character long because the null zero appears in the array immediately after the a.
To sum up character arrays, the following refer to individual array elements (single characters):
names[ 2] and ( names+1) [ 1]
The following refer to addresses only, and as such, you can print the full strings with cout :
names and ( names+4)
The following examples are a little different from most you have seen. They do not perform “real-world” work, but were designed as study examples for you to familiarize yourself with this new method of array referencing. The next few chapters expand on these methods.
Examples
- The
following program stores the numbers from 100 to 600 in an array, then prints elements using the new method of array subscripting.
/ / Fil ename: C24REF1. CPP
/ / Pr i nt el ement s of an i nt eger arr ay i n di ff er ent ways. #i ncl ude <i ost r eam. h>
voi d mai n()
{
i nt num[ 6] = { 100, 200, 300, 400, 500, 600} ;
cout |
<< |
“ num[ 0] i s \t ” << num[ 0] << “ \ n” ; |
||||||
---|---|---|---|---|---|---|---|---|
cout |
<< |
“( num+0) [ 0] i s \t ” << ( num+0) [ 0] << “ \ n” ; |
||||||
cout |
<< |
“( num- 2) [ 2] i s \t ” << ( num- 2) [ 2] << “ \ n\ n” ; |
||||||
cout |
<< |
“ num[ 1] i s \t ” << num[ 1] << “ \ n” ; |
||||||
cout |
<< |
“( num+1) [ 0] i s \t ” << ( num+1) [ 0] << “ \ n\ n” ; |
||||||
cout |
<< |
“ num[ 5] i s \t ” << num[ 5] << “ \ n” ; |
||||||
cout |
<< |
“( num+5) [ 0] |
i s |
\t ” |
<< |
( num+5) [ 0] |
<< |
“ \ n” ; |
cout |
<< |
“( num+2) [ 3] |
i s |
\t ” |
<< |
( num+2) [ 3] |
<< |
“ \ n\ n” ; |
cout |
<< |
“( 3+num) [ 1] i s \t ” << ( 3+num) [ 1] |
<< “ \ n” ; |
|||||
cout |
<< |
“ 3+num[ 1] i s \t ” << 3+num[ 1] << |
“ \ n” ; |
r et ur n;
}
Here is the output of this program:
num[ 0] i s |
100 |
|
---|---|---|
( num+0) [ 0] |
i s |
100 |
( num- 2) [ 2] |
i s |
100 |
num[ 1] i s |
200 |
|
---|---|---|
( num+1) [ 0] |
i s |
200 |
num[ 5] i s |
600 |
|
( num+5) [ 0] |
i s |
600 |
( num+2) [ 3] |
i s |
600 |
( 3+num) [ 1] |
i s |
500 |
3+num[ 1] i s |
203 |
- The
following program prints strings and characters from a character array. The cout s all print properly.
/ / Fil ename: C24REF2. CPP
/ / Pr i nt s el ement s and st r i ngs f r om an arr ay. #i ncl ude <i ost r eam. h>
voi d mai n()
{
char names[] ={ ‘ T’ , ’ e’ , ’ d’ , ’ \ 0' , ’ E’ , ’ v’ , ’ a’ , ’ \ 0' ,
’ S’ , ‘ a’ , ’ m’ , ’ \ 0' } ;
/ / Must use ext r a per cent ( %) t o pr i nt %s and %c. cout << “ names “ << names << “ \ n” ;
cout << “ names+0 “ << names+0 << “ \ n” ; cout << “ names+1 “ << names+1 << “ \ n” ; cout << “ names+2 “ << names+2 << “ \ n” ; cout << “ names+3 “ << names+3 << “ \ n” ; cout << “ names+5 “ << names+5 << “ \ n” ; cout << “ names+8 “ << names+8 << “ \ n\ n” ;
cout << “( names+0) [ 0] “ << ( names+0) [ 0] << “ \ n” ;
cout << “( names+0) [ 1] “ << ( names+0) [ 1] << “ \ n” ;
cout << “( names+0) [ 2] “ << ( names+0) [ 2] << “ \ n” ;
cout << “( names+0) [ 3] “ << ( names+0) [ 3] << “ \ n” ;
cout << “( names+0) [ 4] “ << ( names+0) [ 4] << “ \ n” ;
cout << “( names+0) [ 5] “ << ( names+0) [ 5] << “ \ n\ n” ;
cout << “( names+2) [ 0] “ << ( names+2) [ 0] << “ \ n” ;
cout << “( names+2) [ 1] “ << ( names+2) [ 1] << “ \ n” ;
cout << “( names+1) [ 4] “ << ( names+1) [ 4] << “ \ n\ n” ;
r et ur n;
}
Study the output shown below by comparing it to the pro- gram. You will learn more about strings, characters, and character array referencing from studying this one example than from 20 pages of textual description.
names Ted names+0 Ted names+1 ed names+2 d names+3 names+5 va names+8 Sam
( names+0) [ 0] T
( names+0) [ 1] e
( names+0) [ 2] d
( names+0) [ 3]
( names+0) [ 4] E
( names+0) [ 5] v
( names+2) [ 0] d
( names+2) [ 1]
( names+1) [ 4] v
Review Question s
The answers to the review questions are in Appendix B.
-
True or
false: You must access an array in the same order you initialized it.
-
Where did the bubble sort get its name?
-
Are the following values sorted in ascending or descending order?
33 |
55 |
78 |
78 |
90 |
102 |
435 |
859 |
---|---|---|---|---|---|---|---|
976 |
4092 |
-
How does C++ use the name of an array?
-
Given
the following array definition:
char t eams[ ] = { ‘ E’ , ’ a’ , ’ g’ , ’l’ , ’ e’ , ’ s’ , ’ \ 0' ,
’ R’ , ‘ a’ , ’ m’ , ’ s’ , ’ \ 0' } ;
What is printed with each of these statements? (Answer “invalid” if the cout is illegal.)
-
cout << t eams;
-
cout << t eams+7;
-
cout << ( t eams+3) ;
-
cout << t eams[ 0];
-
cout << ( t eams+0) [ 0];
-
cout << ( t eams+5) ;
Review Exercise s
-
Write
a program to store six of your friends’ ages in a single array. Assign the ages in random order. Print the ages, from low to high, on-screen.
-
Modify the program in Exercise 1 to print the ages in de- scending
order.
-
Using
the new approach of subscripting arrays, rewrite the programs in Exercises 1 and 2. Always put a 0 in the sub- script brackets, modifying the address instead (use
( ages+3) [ 0] rather than ages[ 3] ).
- Sometimes
parallel arrays are used in programs that must track more than one list of values that are related. For in- stance, suppose you had to maintain an inventory, tracking the integer part numbers, prices, and quantities of each item. This would require three arrays: an integer part number array, a floating-point price array, and an integer quantity array. Each array would have the same number of elements (the total number of parts in the inventory). Write a program to maintain such an inventory, and reserve enough elements
for 100 parts in the inventory. Present the user with an input screen. When the user enters a part number, search the part number array. When you locate the position of the part, print the corresponding price and quantity. If the part does not exist, enable the user to add it to the inventory, along with the matching price and quantity.
Summary
You are beginning to see the true power of programming languages. Arrays give you the ability to search and sort lists of values. Sorting and searching are what computers do best; comput- ers can quickly scan through hundreds and even thousands of values, looking for a match. Scanning through files of paper by hand, looking for just the right number, takes much more time. By step- ping through arrays, your program can quickly scan, print, sort, and calculate a list of values. You now have the tools to sort lists of numbers, as well as search for values in a list.
You will use the concepts learned here for sorting and search- ing lists of character string data as well, when you learn a little more about the way C++ manipulates strings and pointers. To help build a solid foundation for this and more advanced material, you now know how to reference array elements without using conventional subscripts.
Now that you have mastered this chapter, the next one will be easy. Chapter 25, “Multidimensional Arrays,” shows you how you can keep track of arrays in a different format called a matrix. Not all lists of data lend themselves to matrices, but you should be prepared for when you need them.