ARRAY: ARRANGEMENT OF DATA You may have heard the following expressions: array of flowers, array of thoughts, or an array of soldiers standing by. What do all these expressions have in common? Each of the above has several alike elements that are arranged in order (one next to the other). In the world of programming, an array has similar properties that are arranged in the memory cells (locations). One cell follows another, all holding information of the same kind. DEFINITION OF AN ARRAY An array is a contiguous and homogeneous memory location identified by a name. The access to each location is done through an index or subscript. Contiguous means the locations (memories) that are continuously next to each other. Homogeneous meaning the cells can only hold data of the same kind. All the data is of the same type: integer, float, etc. The index is a number that represents each room, beginning with 0 and ending with a defined maximum value. The index uniquely identifies each cell allowing access to a corresponding location. HOW DO YOU DECLARE A VARIABLE ARRAY? The way to declare an array is the same as declaring other single variables, such as int x, except that the maximum size of the array must be specified, for example int x[10]. To declare an array, start with the data type, give the array a name, and specify the maximum size of the array by enclosing the number of elements in brackets. The following line of code illustrates the above process: int item[10]; The variable item is declared as an array of 10 locations that each holds an integer value. ARRAY SIZE AND ITS RANGE When declaring an array, the size determines the number of memory locations that are reserved for the array. Note that the index of the array starts at zero rather than one. For example, and array of size ten, the index ranges from zero to nine. Why zero instead of one? One answer is that the internal memory addresses start from zero. Therefore, the compiler doesn't need to adjust the conversion of an array to its address. In the following array declaration, note the array's range runs from zero (0) to nine (9). int item[ 10 ]; // Array range of 0 to 9 will access each element of the array. ARRAY IS TO REMEMBER: EXAMPLES - WHAT WOULD BE THE OUTPUT? Look at the programs of Figure 5.1a and 5.1b. What is the output of each? What is the difference between each of the programs? In the program of Figure 5.1a, x is a single variable. In program of Figure 5.1b, x is an array with two different memory locations. When x represents a single variable memory location, the new value will replace the old value. However, when x is an array, each value can be stored in its own place via a corresponding index, such as 0, for x [0] and 1, for x [1].
CAN YOU LIVE WITHOUT AN ARRAY? There are times when you want to process data back and forth. How is this possible? One solution is to place the entire input data into an array, and revisit the array as many times as you want. One example where an array is a necessity is in sorting a series of input data (e.g. 3 12 7 5 8 1). You must fill the array with input data and process the array back and forth by moving the data around until the array is sorted (1357812). Arrays are essential in retaining the data and manipulating it within a program. CONVERSION TO ARRAY-PAYROLL PROGRAM For the moment, look at this program and the task is to convert this program to its array-based version. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. long int empid; 5. int hoursworked, overtimehours; 6. float hourlyrate, regularpay, overtimepay, grosspay ; 7. while( cin >> empid >>hoursworked >> hourlyrate ){ 8. if( hoursworked > 40 ){ 9. overtimehours = hoursworked - 40; 10. overtimepay = overtimehours * hourlyrate * 1.5; 11. regularpay = 40 * hourlyrate; 12. }//IF 13. else{ 14. overtimehours = 0; 15. overtimepay = 0; 16. regularpay = hoursworked * hourlyrate; 17. }//ELSE 18. grosspay = regularpay + overtimepay; 19. cout << " EMPLOYEE ID IS " << empid << endl; 20. cout << " OVERTIME PAY IS " << overtimepay << endl; 21. cout << " GROSS PAY IS " << grosspay << endl; 22. }//WHILE 23. return 0; 24. }//MAINFigure 5.2a - A version of the Payroll Program without using arrays. The program of Figure 5.2b uses arrays and is equivalent to the payroll program of Figure 5.2a. You may realize there is not much difference between these programs, except for the insertion of brackets and indices, e.g. empid[i]. The purpose of this conversion is to help you to understand arrays. At the moment, we are not concerned with the program's efficiency and realize that the output of both programs will be the same. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int empid[ 100 ], i = 0; 5. int hoursworked[ 100 ], overtimehours[ 100 ]; 6. float hourlyrate[ 100 ], regularpay[ 100 ]; 7. float overtimepay[ 100 ],grosspay[ 100 ]; 8. while( cin >> empid[ i ] >> hoursworked[ i ] >> hourlyrate[ i ] ){ 9. if( hoursworked[ i ] > 40 ){ 10. overtimehours[ i ] = hoursworked[ i ] - 40; 11. overtimepay[ i ] = overtimehours[ i ] * hourlyrate[ i ] * 1.5; 12. regularpay[ i ] = 40 * hourlyrate[ i ]; 13. }//IF 14. else{ 15. overtimehours[ i ] = 0; 16. overtimepay[ i ] = 0; 17. regularpay[ i ] = hoursworked[ i ] * hourlyrate[ i ]; 18. }//ELSE 19. grosspay[ i ] = regularpay[ i ] + overtimepay[ i ]; 20. cout << " EMPLOYEE ID IS "<< empid[ i ] << endl; 21. cout << " OVERTIME PAY IS " << overtimepay[ i ] << endl; 22. cout << " GROSS PAY IS " << grosspay[ i ] << endl; 23. i = i + 1; 24. }//WHILE 25. return 0; 26. }//MAINFigure 5.2b - A version of the Payroll Program using arrays. 1645 41 18.10 8932 40 20.00 7104 60 15.99 2816 25 50.00 5387 30 16.99Figure 5.2c -- Input File named payroll.in used for the programs of Figure 5.2a and Figure 5.2b. EMPLOYEE ID IS 1645 OVERTIME PAY IS 27.15 GROSS PAY IS 751.15 EMPLOYEE ID IS 8932 OVERTIME PAY IS 0 GROSS PAY IS 800 EMPLOYEE ID IS 7104 OVERTIME PAY IS 479.7 GROSS PAY IS 1119.3 EMPLOYEE ID IS 2816 OVERTIME PAY IS 0 GROSS PAY IS 1250 EMPLOYEE ID IS 5387 OVERTIME PAY IS 0 GROSS PAY IS 509.7Figure 5.2d -The output of the programs of Figures 5.2a and 5.2b. WHEN TO USE AND WHEN NOT TO USE ARRAYS A common use of an array is when we want to statistically or analytically evaluate input data. Arrays are useful when there is more than one data of the same type and when the data needs to be revisited. The following are some examples of array assignments: player[ 5 ] = 10; // Players and their scores room[ 123 ] = 2; // Room number and number of guests in each room day[ 1 ] = 75; // Days and its temperatureBesides tracking the data, other information such as mean, median, minimum, maximum, etc. can be found. To find the median, first the data has to be sorted, and then the middle number needs to be accessed. In this case, it is necessary to use an array. There is no need to use an array if the required computation or request can be fulfilled with one trace of the data. For example, finding the total or search for an id number. ARRAY: RANDOM ACCESS You can access any element in an array by using the array name and index. This type of access is called Random Access because there is no need to pass through the other elements of the array to get to the required element. Ordinary access of an input file is not in random, but in sequential order where the input data is accessed one after another. By reading the file into array you can access the data randomly, and as a result the processing speed is enhanced. DUMP THE INPUT DATA INTO AN ARRAY AND THEN MANEUVER AROUND Input data can be read into an array one element at a time into each room (location) as long as there is room in the array and there is input data available. The program of Figure 5.3a reads a series of numbers into an array called tbl. The program displays the first, middle and the last element of the array. 1. #include <iostream> 2. using namespae std; 3. const int MAXSIZE = 10; 4. main(){ 5. int tbl[ MAXSIZE ], n; 6. n = 0; 7. while( ( n < MAXSIZE ) && ( cin >> tbl[ n ] ) ) { n++; } 8. cout << "FIRST ELEMENT " << tbl[ 0 ] << endl; 9. cout << "MIDDLE ELEMENT " << tbl[ n / 2 ] << endl; 10. cout << "LAST ELEMENT " << tbl[ n - 1 ] << endl; 11. return 0; 12. }//MAINFigure 5.3a - Program illustrates reading data into an array and then accessing the first, middle and last elements of the array 1 2 3 4 5 6 7 8 9 10Figure 5.3b -(left) File named numbers.in is used to read load the array element tbl. FIRST ELEMENT 1 MIDDLE ELEMENT 6 LAST ELEMENT 10Figure 5.3c - The output of the program of Figure 5.3a. AN ARRAY NEEDS TO BE ACCOMPANIED BY A LOOP In order to place the input data into an array and to maneuver through the array, it is necessary to have a loop. The program listed in Figure 5.4a reads a series of numbers into an array called tbl. The program reassigns each element of the array by 10% and then displays the whole array. 1. #include <iostream> 2. using namespace std; 3. const int MAXSIZE = 20; 4. main(){ 5. int i, n = 0; 6. int tbl[ MAXSIZE ]; 7. while( cin >> tbl[ n ] ) n++; 8. i = 0; 9. while( i < n ){ 10. tbl[ i ] = tbl[ i ] + tbl[ i ] * 0.10; 11. i++; 12. }//WHILE 13. i = 0; 14. while ( i < n){ 15. cout << tbl[ i ] << endl; 16. i++; 17. }//WHILE 18. return 0; 19. }//MAINFigure 5.4a - The program reads data into an array with loop one. Loop two increments the value of each element in the array by 10%. The last loop displays the contents of the entire array.
It is preferable to use the for loop instead of the while loop, whenever the loop control variable, initial value, and final value are known. The for loop has a form where the initialization, testing, and updating of the loop can all be done in a single line. The program of Figure 5.5 illustrates the proper usage of the for and the while loops. for( intialvariable ; testvariable ; updatevariable ) { // body of the loop; } 1. #include <iostream> 2. using namespace std; 3. const int MAXSIZE = 20; 4. main(){ 5. int i, n = 0; 6. int tbl[ MAXSIZE ]; 7. while( cin >> tbl[ n ] ) n++; 8. for( i = 0 ; i < n ; i++ ){ 9. tbl[ i ] = tbl[ i ] + tbl [ i ] * 0.10; 10. }// FOR 11. for( i = 0 ; i < n ; i++ ){ 12. cout << tbl[ i ] << endl; 13. }// FOR 14. return 0; 15. }//MAINFigure 5.5 - Proper usage of while and for loops. Compare the program to Figure 5.4a to fully understand the difference. Both programs will produce the output of Figure 5.4c using the same data file of Figure 5.4b. ACCUMULATING THE SUM (SUMMATION) Once the input data is in an array, how do you sum up the array? An array can be a series of unit costs, temperatures, exam points or a bank's transactions (+$100 deposit, -$100 withdrawal). How do you keep track of the total? You must start with a variable presumably called sum to accumulate each element of the array. As each element of the array is accumulated within the sum, a new value is assigned to the sum to reflect the change. The accumulating variable must be initialized to zero, to insure that it contains no other values at the starting point. Figure 5.6a illustrates the summation process and uses the data file named numbers.in from Figure 5.3b. The output of the program is shown in Figure 5.6b. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int num[100], sum, n = 0; 5. sum = 0; 6. while( cin >> num[ n ] ) n++; 7. for( int i = 0 ; i < n ; i++ ){ 8. sum = sum + num[ i ]; 9. }// FOR 10. cout << "THE SUM OF THE NUMBERS IS " << sum << endl; 11. return 0; 12. }//MAINFigure 5.6a - The program sums all numbers that read into the array named num. THE SUM OF THE NUMBERS IS 55Figure 5.6b - The output of Figure 5.6a using the input file named numbers.in. SUMMATION: EXAMPLES Table 5.1 demonstrates how elements of an array are added. For these examples, the loop and initialization are not shown.
MULTIPLYING THE NUMBERS (PRODUCTS) If you have a series of numbers stored in an array, how do you multiply all the elements of the array? As each element of the array is multiplied you have to keep track of the result, so that it can be used for the next number on the next round of the loop. This is the same as summation except the initialization of the product variable should be 1 instead of 0; and obviously you should use the multiplication sign ( * ) instead of the addition sign ( + ). ARRAY OF CHARACTERS While the first initial of your first name is one character, how many characters make up your first name? Your name, telephone, social security number, and your license plate consist of an array of characters. Table 5.2 illustrates some examples of declaring an array of characters.
BUILDING A STRING: ARRAY OF CHARACTERS WITH NULL In C/C++ a string is an array of characters terminated by a null character. A null character is represented by '\0', NULL, or its ASCII's value of zero ( 0 ). See Figure 5.8a and 5.8b for an example of a program and its output respectively. INPUT AND OUTPUT OF THE STRING You can input a string by using cin instead of building the string character by character. The drawback of using the cin to enter a string is that a blank space terminates the end of the string. A string can be displayed by using cout. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int i = 0; 5. char name[15]; 6. while( ( i < 15 ) && ( cin >> name[ i ] ) ){ 7. cin >> name[ i ]; 8. i++; 9. }//WHILE 10. name[ i ] = NULL; // name[ 15 ] = 0; 11. cout << "NAME IS " << name << endl; 12. return 0; 13. }//MAINFigure 5.7a - Entering a name character by character. abcdefghijklmno NAME IS abcdefghijklmnoFigure 5.7b - Sample output of Figure 5.8a. INPUT/ OUTPUT STRING: C VERSUS C++ To input data, C uses scanf, while C++ uses cin for the standard input. To output data, C uses printf, while C++ uses cout. The scanf and printf system words are included in the stdio.h header file while cin and cout are included in the iostream.h header file. Formatting of data in scanf and printf must be specified, while formatting for cin and cout specification is not necessary. Figure 5.8a and 5.8b shows a program written in C and C++ illustrating how to enter a first name, and last name. Figure 5.8c shows the output of both programs. 1. #includeFigure 5.8a - C program showing the input and output of a string. Remember that when scanf or cin creates a string, the null character is inserted at the end of the string. Having a null at the end of an array of characters makes string manipulation easier. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. char firstname[ 15 ], lastname[ 17 ]; 5. cout << "ENTER FIRST NAME: "; 6. cin >> firstname; 7. cout << "ENTER LAST NAME: "; 8. cin >> lastname; 9. cout << "\nFIRST NAME IS " << firstname << endl; 10. cout << "LAST NAME IS " << lastname << endl; 11. return 0; 12. }//MAINFigure 5.8b - C++ program showing the input and output of a string. ENTER FIRST NAME: ALIREZA ENTER LAST NAME: EBRAHIMI FIRST NAME IS ALIREZA LAST NAME IS EBRAHIMIFigure 5.8c -Output of the programs of Figures 5.8a and 5.8b. C scanf AND ARRAY'S NAME Observe the input function scanf has the following form: scanf( "%dataTypeFormat", &variableName );The ampersand ( & ) represents for the address of a variable. However, if the variable is an address by itself then there is no need for the &. The name of array (without the brackets) is an address. Therefore, there is no need for & before the array name. The sample code of figure 5.9 illustrates this explanation. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. • 5. • 6. • 7. printf(" WHAT IS YOUR FIRST NAME: " ); 8. scanf( "%s", firstname ); 9. • 10. • 11. • 12. return 0; 13. }//MAINFigure 5.9 - Example of inputting an array using C. ARRAY INITIALIZATION Assigning a zero, blank character can initialize an array, or null, depending on the type of data the array contains. The initialization of an array can be done with a loop going through the entire array. For example, the following two lines of code initialize all the array values to zero for an array named number. int number[ 15 ]; for( int i = 0 ; i < 15 ; i++ ) number[ i ] = 0;Initialization of an array can be done at the time of the array declaration. For example, the array named daysinmonth is initialized where the array is declared in the program of Figure 5.10a. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int daysinmonth[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 5. for( int i = 0 ; i < 12 ; ++i ){ 6. cout << "MONTH " << i +1 << " DAYS " << daysinmonth[ i ] << endl; 7. }// FOR 8. return 0; 9. }//MAINFigure 5.10a - Syntax for initializing an array at declaration time. MONTH 1 DAYS 31 MONTH 2 DAYS 28 MONTH 3 DAYS 31 MONTH 4 DAYS 30 MONTH 5 DAYS 31 MONTH 6 DAYS 30 MONTH 7 DAYS 31 MONTH 8 DAYS 31 MONTH 9 DAYS 30 MONTH 10 DAYS 31 MONTH 11 DAYS 30 MONTH 12 DAYS 31Figure 5.10b - The output of the program of Figure 5.10a. KEEP NUMBER OF FREQUENCIES There are situations where you want to find the frequency of a number, item, or an object. For example, keeping records of a survey or finding what letter or digit is used the most in a book, paragraph, or in an e-mail. You may want to keep track of scores of players or keep records of a survey. See figure 5.11a for a program that keeps track of a letters frequency. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. char ch; 5. int freqletter[200]; 6. for( ch = 'a' ; ch <= 'z' ; ch++ ){ 7. freqletter[ ch ] = 0; }// initialize the array 8. cout << "Enter some lower case letters ( Ctrl + Z to End ): "; 9. while( cin >> ch ){ 10. freqletter[ ch ] = freqletter[ ch ] + 1; } 11. cout << "\n\n\n\t\tLETTER FREQUENCY "<<endl<<endl; 12. int lineCounter = 1; 13. for( ch = 'a' ; ch <= 'z' ; ch++ ){ 14. cout << " " << ch << " = " << freqletter[ ch ]; 15. if( lineCounter >= 5 ){ 16. cout <<endl; 17. lineCounter = 0; }//IF 18. lineCounter++; }// FOR 19. cout <<endl; 20. return 0; 21. }//MAINFigure 5.11b - Sample output to the frequency program of Figure 5.11a. Enter some lower case letters ( Ctrl + Z to End ): ebrahimi is great LETTER FREQUENCY a = 2 b = 1 c = 0 d = 0 e = 2 f = 0 g = 1 h = 1 i = 3 j = 0 k = 0 l = 0 m = 1 n = 0 o = 0 p = 0 q = 0 r = 2 s = 1 t = 1 u = 0 v = 0 w = 0 x = 0 y = 0 z = 0Figure 5.11b - Sample output to the frequency program of Figure 5.11a. The below line of code will keep track of the ASCII characters including blanks and digits: for( ch = 0 ; ch <= 255 ; ch++ ) Similarly, we keep track of player scores by the following statements: cin >> playernum >> newscore; playerscore[ playernum ] = playerscore[ playernum ] + newscore;ARRAY OF ARRAY: TWO DIMENSIONAL ARRAY When data is represented as a tabular form, it is natural to use a two-dimensional array rather than a one-dimensional array. In two-dimensional arrays, there are two subscripts. One subscript is for the number of rows, while the other subscript is for the number of columns. A tic-tac-toe board can be shown as a two dimensional array as follows: char tictactoe[ 3 ][ 3 ]; // tictactow[ row ][ column]Tic-Tac-Toe can also be shown with a one-dimensional array or even nine separate variables, such as follows: char tictactoe[9]; char ttt0, ttt1, ttt2, ttt3, ttt4, ttt5, ttt6, ttt7, ttt8; MULTIDIMENSIONAL ARRAY: ROBOT'S ARM POSITION A three or more dimensional array can be declared and used the same way as a two dimensional array. For example, a three dimensional array representing the position of a robot's arm by assigning one subscript for the row, one subscript for the column and one subscript for the height. Just remember that computer memory consists of a series of linear addresses. Therefore, a multidimensional array must be converted to a linear address by the compiler. The following declaration shows a three dimensional array: int robotposition[ row ][ column ][ height ]; However, if there were many robots we could have added another ( fourth )dimension: int robotposition[ number ][ row ][ column ][ height ]; ARRAY OF STRINGS How do you declare an array of strings? A string is an array of characters. Therefore, we can use another array, such as an array of employee names. Each employee has a name (maximum of 15 character long) and there are 100 employees. The declaration is shown below. char employeename[ 100 ][ 15 ]; PARALLEL ARRAYS Two separate arrays that are related through their subscripts and have the same value are known as parallel arrays. An example of a parallel array is one array named id and another named price, where the item's id and the related item's price are stored in respective locations via a subscript value. With the subscript 0, the id[ 0 ] and its related price[ 0 ] can be accessed. MATRIX MULTIPLICATION While matrix addition and subtraction is straight forward, the multiplication of two matrices requires attention. Take a row of the first matrix and multiply it by an associated column of the second matrix (row 1 with column 1). Then multiply corresponding elements and add them to make one element of the third matrix. Note that in the multiplication of two matrices, the number of columns of the first matrix must be the same as the number of rows in the second matrix. 1. #include <iostream.> 2. using namespace std; 3. main(){ 4. int a[20][20]; 5. int b[20][20],c[20][20]; 6. int rowa, cola, colb, i,j,k; 7. cout << "ENTER THE NUMBER ROWS OF MATRIX A: "; 8. cin >> rowa; 9. cout << "ENTER THE NUMBER OF COLUMNS OF MATRIX A: "; 10. cin>>cola; 11. cout<<"BY DEFAULT THE NUMBER OF ROWS IN MATRIX B IS: "<<cola<<endl; 12. cout <<"ENTER THE NUMBER OF COLUMNS OF MATRIX B: "; 13. cin >> colb; 14. //FIRST MATRIX INITIALIZATION 15. cout<<"ENTER THE VALUES FOR MATRIX A: "<<endl<<endl; 16. for( i = 0 ; i < rowa ; i++){ 17. for( j = 0 ; j < cola ; j++ ){ 18. cout<<"MATRIX A: ROW "<<i+1<<" COLUMN "<<j+1<<": "; 19. cin >> a[ i ][ j ]; 20. }// FOR i 21. }// FOR j 22. //SECOND MATRIX INITIALIZATION 23. cout<<"ENTER THE VALUES FOR MATRIX B: "<<endl<<endl; 24. for( i =0 ; i < cola ; i++ ){ 25. for( j = 0 ; j < colb ; j++ ) { 26. cout<<"MATRIX B: ROW "<<i+1<<" COLUMN "<<j+1<<": "; 27. cin >> b[ i ][ j ]; 28. } // FOR i 29. }// FOR j 30. //MULTIPLICATION 31. for( i = 0 ; i < rowa ; i++ ){ 32. for ( j = 0 ;j < colb ; j++ ){ 33. c[ i ][ j ] = 0; 34. for( k = 0 ; k < cola; k++ ){ 35. c[ i ][ j ] = c[ i ][ j ] + a[ i ][ k ] * b[ k ][ j ]; 36. }// FOR k 37. }// FOR j 38. }// FOR I 39. for( i =0 ; i < rowa ; i++ ){ 40. for( j = 0 ; j < colb ; j++ ) { 41. cout << c[ i ][ j ]<<" "; 42. } // FOR i 43. cout<<endl; 44. }// FOR j 45. return 0; } //MAINFigure 5.12a - The multiplication of two matrices. ENTER THE NUMBER ROWS OF MATRIX A: 2 ENTER THE NUMBER OF COLUMNS OF MATRIX A: 3 BY DEFAULT THE NUMBER OF ROWS IN MATRIX B IS: 3 ENTER THE NUMBER OF COLUMNS OF MATRIX B: 2 ENTER THE VALUES FOR MATRIX A: MATRIX A: ROW 1 COLUMN 1: 2 MATRIX A: ROW 1 COLUMN 2: 2 MATRIX A: ROW 1 COLUMN 3: 1 MATRIX A: ROW 2 COLUMN 1: 1 MATRIX A: ROW 2 COLUMN 2: 2 MATRIX A: ROW 2 COLUMN 3: 1 ENTER THE VALUES FOR MATRIX B: MATRIX B: ROW 1 COLUMN 1: 1 MATRIX B: ROW 1 COLUMN 2: 2 MATRIX B: ROW 2 COLUMN 1: 1 MATRIX B: ROW 2 COLUMN 2: 1 MATRIX B: ROW 3 COLUMN 1: 1 MATRIX B: ROW 3 COLUMN 2: 3 5 9 4 7Figure 5.12b - Sample output of the multiplication of two matrices. BUILDING A DATA STRUCTURE WITH AN ARRAY The way data is stored, retrieved, and now the way data interacts in an array, as well as the operations applied to the data introduces an important topic in computer problem solving known as data structure. One way to implement the data structure is through the manipulation of an array. The following is a list of data structures that can be implemented by using an array: stacks, queues, sets, linked lists, trees, and graphs. For example, if an array is restricted to storing data one after the other and the first retrieval is the last data that has been stored (last in first out), this creates a data structure known as a stack. SEARCHING AN ELEMENT OF AN ARRAY While data is stored in an array, searching the data is less complicated. A loop with an if statement does the job, since the end of the data is known. Searching through the array is faster than searching through the file to acquire data and compare it. MODIFYING AN ELEMENT OF AN ARRAY A simple assignment statement will replace a value of an element of an array with a new value. For example in table[ 5 ] = 7 the value 7 replaces the old value of table[ 5 ]. DELETING AN ELEMENT OF AN ARRAY Note, an array is a contiguous homogenous memory location; therefore, deleting an element does not delete the location in the array. As a result, there is a gap when data is deleted. When the data id is deleted a dummy value, such as 0 or 99999, can replace the numeric data, and an empty space ( ' ' ) or empty string (" " ) can replace the character and string respectively. Several deletions of data can make an array useless; therefore, it is preferable to shift the data up to remove the gaps. Shifting an array requires a substantial amount of shuffling time. SORTING: AN ARRAY IS A NECESSITY An array is a necessity when we want to sort a series of data elements. In order to sort a series of data elements, it is necessary to scan through the data back and forth to compare them. Following are the three major steps to sort a series of data:
1. #include <iostream> 2. using namespace std; 3. main(){ 4. int table[ ] = { 5, 1, 3, 99, 8, 12, 7, 8, 14 }; 5. int i, j; 6. int n=9; 7. for( i = 0 ; i < n - 1 ; i++ ){ 8. for( j = n - 1 ; j > i ; j-- ){ 9. if( table[ j ] < table[ j - 1 ] ){ 10. int hold = table[ j ]; 11. table[ j ] = table[ j - 1 ]; 12. table[ j - 1 ] = hold; 13. } // end if 14. } // end j 15. } // end i 16. cout << "SORTED DATA" << endl; 17. for( i = 0 ; i < n ; i++ ){ 18. cout << table[ i ] << " " ; 19. }// FOR 20. return 0; 21. }//MAIN Figure 5.13a - Sorting an array. SORTED DATA 1 3 5 7 8 8 12 14 99Figure 5.13b - Output of the program of Figure 5.13a. ARRAY AND PAYROLL: PROGRAM EXTENSION In order to expand the previous Payroll Program to incorporate arrays, all the employee variables will be converted to arrays, which includes input, computational, and the output variables. The first step is to read the entire data, either interactively or from a data file, into input variable arrays. Now that the entire input data is in the array we can process it for each task separately such as the computation of all employees overtime pay, which are stored into the array. Note that by having all the data placed into array variables, the program can take advantage of this and focus to process each task separately in conjunction with the loop. We want to extend the payroll program to print a tabular report consisting of employee hours worked, hourly rate, gross pay, tax amount, and net pay. For example, overtime pay for all employees can be computed and stored into an array so it can be processed at later time. Similarly, the gross pay and other computations can be done separately. The program will expand in future chapters to include a search to look for employee ID's. If the search is successful, the employee's information will be displayed. Otherwise, a failure message will be displayed. Figure 5.14a lists the expanded Payroll Program. 1. #include <iostream> 2. #include <iomanip> 3. using namespace std; 4. main(){ 5. char empid[ 100 ][ 12 ]; 6. char fname[ 100 ][ 14 ], lastname[ 100 ][ 15 ]; 7. int hw[ 100 ]; 8. double gp[ 100 ], np[ 100 ], hr[ 100 ], taxrate[100], taxamt[ 100 ]; 9. int counter = 0; 10. int i; 11. cout<<"ENTER EMP ID, FNAME, LNAME, HRS WORKED, HRLY RATE ctrl z to end"<<endl; 12. while( cin>>empid[counter]>>fname[counter]>>lastname[counter]>>hw[counter]>> hr[counter]) 13. counter=counter+1; 14. for ( i=0; i<counter; i++){ 15. gp[i] = hw[i] * hr[i];}//end grosspay for loop 16. for (i=0; i<counter; i++){ 17. if (gp[i]>500) taxrate[i] = .30; 18. else if (gp[i]>200) taxrate[i]=.20; 19. else taxrate[i] = .10; 20. }// FOR 21. for ( i=0; i<counter; i++){ 22. taxamt[i] = gp[i] * taxrate[i];}//end taxamount for loop 23. for ( i=0; i<counter; i++){ 24. np[i] = gp[i] - taxamt[i];}//end netpay for loop 25. cout<<endl; 26. cout<<setw(14)<<"EMPLOYEE ID"<<setw(16)<<"FIRST NAME"<<setw(17) 27. <<"LAST NAME" <<setw(4)<<"HW"<<setw(5)<<"HR"<<setw(6) 28. <<"GROSS"<<setw(6)<<"TAX"<<setw(9)<<"NET PAY"<<endl<<endl; 29. for (i=0; i<counter; i++){ 30. cout<<setw(14)<<empid[i]<<setw(16)<<fname[i]<<setw(17)<<lastname[i]<<setw(4) 31. <<hw[i]<<setw(5)<<hr[i]<<setw(6)<<gp[i]<<setw(6)<<taxamt[i]<<setw(9)<<np[i]<<endl; 32. }// FOR 33. return 0; 34. }//MAINFigure 5.14a - Payroll program with the use of arrays. PLEASE ENTER THE EMP ID, FNAME, LNAME, HRS WORKED, AND HRLY RATE cntrl z to end 111-22-3333 JOSEPH SMITH 40 10 333-44-5555 BETTY JANE 30 20 EMPLOYEE ID FIRST NAME LAST NAME HWHR GROSSTAXNET PAY 111-22-3333 JOSEPH SMITH 40 10 400 80 320 333-44-5555 BETTY JANE 30 20 600 180420 Press any key to continueFigure 5.14b - The output to the Payroll Program of Figure 5.15a. CLOSING REMARKS AND LOOKING AHEAD Each variable holds a value and when a new value is assigned to the same variable, the old value is replaced. In order to keep track of the various values of a variable, we need to have several locations assigned to the variable. Assigning several locations to a variable where locations are next to each other creates an array. An array element is accessed through its subscript (index). A loop is used as a tool to traverse through all elements of an array. The way data is stored, retrieved, and manipulated in an array brings forth the concept of data structure, which will be described in a future chapter. We examined several different arrays of simple data types. Yet, we have not looked at other kinds of arrays, such as arrays of pointers, arrays of structures, arrays of objects, and pointers to arrays. Arrays can structure program codes in such a way that each subtask of a problem can be tackled separately. This grouping of related codes introduces the concept of functions, which enhance the use of arrays. The next chapter introduces the concept of the function. |