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.
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.
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 arrays range runs from zero (0) to nine (9).
int item[ 10 ]; // Array range of 0 to 9 will access each element of the array.
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].





![Text Box: Figure 5.1d Output of Figure 5.1b. Notice that the original value of x is not overwritten as x [0] and x[1] are separate memory locations using the value of x.](chapter_5_files/image006.gif)
![Text Box: 1. #include <iostream>
2. using namespace std;
3. main(){
4. int x[2];
5. x[0] = 5;
6. x[1] = 10;
7. cout << X WAS << x[0]<<endl
8. << X IS << x[1] << endl;
9. return 0;
10. }//MAIN](chapter_5_files/image007.gif)

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 (1 3 5 7 8 12). Arrays are essential in retaining the data and manipulating it within a program.
CONVERSION TO ARRAYPAYROLL PROGRAM

![]()
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 programs efficiency and realize that the output of both programs will be the same.
![Text Box: 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. }//MAIN](chapter_5_files/image010.gif)
![]()


![]()

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:
![Text Box: 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 temperature](chapter_5_files/image015.gif)
Besides 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.
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.
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.


![]()

![Text Box: 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. }//MAIN](chapter_5_files/image020.gif)

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.
![Text Box: 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. }//MAIN](chapter_5_files/image022.gif)


![]()


FOR LOOP INSTEAD OF WHILE LOOP
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.
![Text Box: 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. }//MAIN](chapter_5_files/image028.gif)
![]()
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.
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.
![Text Box: 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. }//MAIN](chapter_5_files/image030.gif)
![]()
![]()

SUMMATION: EXAMPLES
Table 5.1 demonstrates how elements of an array are added. For these examples, the loop and initialization are not shown.
|
Summation Examples
|
|
sumoftemperature = sumoftemperature + temperature [i];
|
|
totalrain = totalrain + rain[ i ];
|
|
sumofscores = sumofscores + scores[ i ];
|
|
balance = balance + transaction[ i ];
|
![]()
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.
|
Character Array Declarations
|
|
|
char initial; |
// declare a single character variable name initial Not an array
|
|
char name[16]; |
// declare an array of characters of length 16 ( 0 to 15 )
|
|
char telephone[14]; |
// declare an array of characters of length 14 ( 0 to 13 )
|
|
char ssn[12]; |
// declare an array of characters of length 12 ( 0 to 11 )
|
|
char memo[1000]; |
// declare an array of characters of length 1000 ( 0 to 999 ) |
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.
![Text Box: 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. }//MAIN](chapter_5_files/image035.gif)
![]()

![]()
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.
![Text Box: 1. #include <stdio.h>
2. main(){
3. char firstname[15], lastname[17];
4. printf( "ENTER FIRST NAME: " );
5. scanf( "%s", firstname );
6. printf( "ENTER LAST NAME: " );
7. scanf( "%s", lastname );
8. printf( "\nFIRST NAME IS %s\n ", firstname );
9. printf( "LAST NAME IS %s\n", lastname );
10. return 0;
11. }//MAIN](chapter_5_files/image039.gif)
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.
![Text Box: 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. }//MAIN](chapter_5_files/image041.gif)
![]()

![]()
C scanf AND ARRAY'S NAME
Observe the input function scanf has the following form:

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.

![]()
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.
![Text Box: 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. }//MAIN](chapter_5_files/image047.gif)
![]()


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.
![Text Box: 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. }//MAIN](chapter_5_files/image050.gif)
![]()

![]()
The below line of code will keep track of the ASCII characters including blanks and digits:
![]()
Similarly, we keep track of player scores by the following statements:
![Text Box: cin >> playernum >> newscore;
playerscore[ playernum ] = playerscore[ playernum ] + newscore;](chapter_5_files/image055.gif)
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:
![Text Box:
char tictactoe[ 3 ][ 3 ]; // tictactow[ row ][ column]](chapter_5_files/image056.gif)
Tic-Tac-Toe can also be shown with a one-dimensional array or even nine separate variables, such as follows:
![Text Box: char tictactoe[9];
char ttt0, ttt1, ttt2, ttt3, ttt4, ttt5, ttt6, ttt7, ttt8;](chapter_5_files/image056.gif)
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 robots 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:
![]()
However, if there were many robots we could have added another ( fourth )dimension:
![]()
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.
![]()
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.
![]()
![]()

![Text Box: 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; } //MAIN](chapter_5_files/image060.gif)
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 ].
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.
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. The first step is to load the array from the data file, or if the data set is small it can be initialized at the point of array declaration or entered through the keyboard.
The following statement will read from the data file.
ifstream fin ( " file.in" ) while (fin>>table[n]) n++;
2. The second step is to scan through the array one by one and compare each two adjacent elements to check if they are in the right order. For example, in ascending order, the first element should be less than the second element and the second element should be less than third element, and so on. If this is not the case the values of two elements should be swapped.
3. The final step is to loop this process when swapping is complete.
The program of Figure 5.13a shows a simple sorting algorithm. The output is shown in Figure 5.13b.
![Text Box: 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](chapter_5_files/image061.gif)
![]()

![]()
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 IDs. 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.
![Text Box: 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. }//MAIN](chapter_5_files/image065.gif)
![]()
![]()

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.
__ 1. The declaration, int empid[10]; will reserve 11 memory locations one after another instead of 10.
__ 2. A sequence of contiguous and homogenous memory locations is known as an array.
__ 3. Every location of an array can have different data types such as int, double, and char.
__ 4. The declaration char name[20][100]; allocates storage for twenty names each 100 characters long.
__ 5. The segment: while(fin>>empid[n]) n++; will dump all the employees ids into an array.
__ 6. The segment: for(i=0; i<n; i++) cout<< empid[i]<<endl; will compute all the employees grosspays.
__ 7. When the data is in an array it is easy to revisit the data with a loop.
__ 8. The index of an array starts with 0 instead of 1. For example, gp[10] has an index range from 0 to 9.
__ 9. To use setw( ) , setiosflags and other io manipulators we need to include the fstream header file.
__ 10. Use of setw( ) in an output routine will create a tabular display.
__ 11. If the data is in an array it is easy to search for data or even sort the data.
__ 12. Elements of an array can be accessed randomly using the array name and index.
__ 13. When declaring an array, the minimum size of the array must be specified.
__ 14. int x=5; x=6; cout<<x<<x<<endl; The values 5 and 6 will be displayed.
__ 15. int x[2]; x[0]=5; x[1]=6; cout<<x[0]<<x[1]<<endl; The values 5 and 6 will be displayed.
__ 16. When you need to process data back and forth (e.g. sorting), it is not recommended to use an array.
__ 17. A program can easily be converted to use arrays by simply adding the index (e.g. emp to emp[i]).
__ 22. To sum a series of numbers you need to initialize the sum = 1;
__ 23. When data is represented in a tabular form, it is natural to use a two-dimensional array.
__ 24. A string is an array of characters terminated by NULL.
__ 25. Several data structures can be implemented by using arrays.
CHAPTER 5 ARRAY ASSIGNMENTS AND CASE STUDY
Q5a) Write a supermarket-pricing program. Program inputs are: itemid, itemname, unitprice, itemquantity, and taxstatus. Use 1 to indicate taxable items and 0 for non-taxable items, and the tax rate should be constant at 10%. Program should compute the subtotal for each item and add the sales tax if the item is taxable, then compute the grand total for the entire purchase. Program outputs should include item id, item name, subtotal, sales tax, and the total price for each item, then print the total sales tax and the grand total.
1234 shoes 25.00 2 1
9834 milk 1.99 1 0
1278 watches 60.00 1 1
9912 bread 1.00 3 0
Expand the above program to read the entire data (regardless of its size) into arrays and give the total number of items purchased. For example, the total number of items purchased in the above data file is 4.
Compute the price for each group of items. Use a for loop instead of while.
priceitems[i] = [i] * quantity[i];
Compute all the itemsalestax.
if (taxable[i] == 1)
itemsalestax[i] = priceitem[i] * 0.10;
else . ;
Compute the total of all the items. Make sure to initialize total to 0.
total = total + [i];
Compute the total sales tax of all items. Make sure to initialize totalsalestax = 0;
totalsalestax = . + itemsalestax[i]
Compute the grandtotal and display total, totalsalestax, and grandtotal.
Q5b) For the following program, find ten syntax errors. Underline the errors and explain why. You may want to recompile the program as you correct the syntax errors.
void main(){
int gp[100];np[1000];
double ta[100],tr[100];
character name[100] 4];
n=1;
while (fin>>hw[n]>>hr[n]) {n--; }//WHILE
for (i=0;i<n;i++){
if( hw[i]> 40 ){ovh=hw[i]-40;
ovp[i]=ovh *hr[i] * 1.2;
regp[i]=40* hr[i];
else if { ovp[i]=0.0;
regp=hw[i]* hr[i]; }
}//OVP
for( i=o; i>n; i+){
gp[i]=reg[i] -ovp[n];}/ FOR
for (i=0;i<n;i++){
if gp[i]>500 then tr[i]=20.00
else if gp[]<200 tr[i]=.10;
else if gp[i]=0.50; }//TR
if (status==M)&&(status==S) ta[i]=tr[i]+0.05;
for(i=0;i<n;i++) ta[i]=gp[i]*tr[i]
for(i=0,i<n,i++) np[i]=gp[i]+ta[i];
for(i=0;i<n;i++){cout<<setw(10)<<NAME<<setw(10)<<GROSS PAY
<<NET PAY<<ENDL;
cout>> name[i]<<gp[i]<<ta[i]<<np[i[;}//OUTPUT
return;
}//End WHILE
{//MAIN
Q5c) For the following program, find five logical errors. You may want to re-execute the program as you fix the logical errors.
void main(){
int gp[100];np[1000];
double ta[100],tr[100];
character name[100] 4];
n=1;
while (fin>>hw[n]>>hr[n]) {n--; }//WHILE
for (i=0;i<n;i++){
if( hw[i]> 40 ){ovh=hw[i]-40;
ovp[i]=ovh *hr[i] * 1.2;
regp[i]=40* hr[i];
else if { ovp[i]=0.0;
regp=hw[i]* hr[i]; }
}//OVP
for( i=o; i>n; i++){
gp[i]=reg[i] -ovp[n];}/ FOR
for (i=0;i<n;i++){
if gp[i]>500 then tr[i]=20.00
else if gp[]<200 tr[i]=.10;
else if gp[i]=0.50; }//TR
if (status==M)&&(status==S) ta[i]=tr[i]+0.05;
for(i=0;i<n;i++) ta[i]=gp[i]*tr[i];
for(i=0;i<n;i++) np[i]=gp[i]+ta[i];
for(i=0;i<n;i++){cout<<setw(10)<<NAME<<setw(10)<<GROSS PAY
<<NET PAY<<ENDL;
cout<< name[i]<<gp[i]<<ta[i]<<np[i[;}//OUTPUT
return;
}//End WHILE
{//MAIN
Q5d) Complete the following grading program by filling in the dots. The program will search by id. It computes students averages and assigns a letter grade to each student. At the end the program, it will ask the user to enter the id and the program will display the grade.
<fstream>
#include <iostream>
;
{ .. int MAXARRAY=25;
int stdid[MAXARRAY], assingscore[MAXARRAY], midscore[MAXARRAY],
.., i,n;
char .;
double averagescore[MAXARRAY];
ifstream fin(studentgrades.in) .
..=0;
while(fin>>stdid[n]>> >>midscore[n]>>finscore[n]){ .}
for(i=0;i<n;i++){
sumscore[i]=assingscore[i]+midscore[i] finscore[i]
averagesocre[i]=sumscore[i]/ ..;
.. (averagescore[i]>90) grade[i]=A;
else if(averagescore[i]>80) . ..=B;
if ( >70) grade[i]=C;
else if(averagescore[i]> ) ..=D
grade[i]=F;}//COMPUTATION
.<< ENTER THE STUDENT ID ;
..>>searched;
for(i=0;i<n;i++){
if(searched== .[i]){
cout<<STUDENTS ID IS: <<<< ;
cout<<STUDENTS AVERAGE GRADE IS: << .. .;
cout<<STUDENT GRADE IS: << <<endl;
break; //FOR
if (i== ) cout<< ..FOUND <<endl;
..
}// .
Q5e) You are to design a grading system from scratch for professor T to determine the grade for each student. The data file contains the following: STUDENTID, MIDTERM, FINAL, and ASSIGNMENT. Show your own data file.
Expand the above program to include arrays to store the student name, students id, the score for midterm, final, assignment, the total and the average score, and the letter grade. You must use separate loops to read the data, compute grades, and print output.
Q5f) Find 10 syntax errors in the following program. Indicate the line number and explain why.
Find 5 logical errors in the following program.
1 # include <iostreem>
2 using namespace std;
3 / / this is an assignment #4b written by John Doe */
4 void main( void )
5 {char name[50][2];
6 long int empid[50];
7 int hw[50], ohw[50],i,n;
8 float grosspay[50],taxamount[50], netpay[50];taxrate[50];
9 doubl regularpay[50], overtimepay[50];
10 ifstream fin (payroll.in);
11 n==1;
12 while(fin>>empid[n]>>name[n]<<hoursworked[n]>>hourlyrate[n]){n++} //read all
13 For (i=0; i<=n; i++){ if (hoursworked[i] >40){
14 ohw[i]=hw-40;
15 overtimepay[n] = ohw[ i]* hourlyrate[i] * 0.5;
16 regularpay[I]= hw[i] * hr[i]; // end overtime
17 elseif( <=40){
18 ohw[i]=0;
19 overtimepay[i]=0* taxrate[0]; ;
20 regularpay[i]= hoursworked[i] * hourlyrate[i]; }
21 grosspay[i]=regularpay[i] + overtimepay[i];
22 }//end compute tax rate /* end of else */
23 for(i=0; i<= n; i++){
24 if (grosspay[i] >500) taxrate[i]= 0.20;
25 else if (grosspay[i] >400 ) taxrate[i]= 10.00;
26 else taxamount[n] =0;
27 grosspay[i]= regpay[i] - overtimepay[i];
28 axamount[i]= grossppay[i] X taxrate[i];
29 netpay[i]=grosspay[i]- taxamount[i];}//
30 }//compute all netpay
31 cout<<setw(20)<<NAME<<setw(20)<<GROSS PAY <<setw(2)<<NET PAY<<endl;
32
33 for(i=0;i>n;i++){ cout<<setwidth(20)<<name[i]<<grosspay[I]<<netpay[i]<<endl;
34 }//end output
35
36 return o;}//end for loop
Q5g) What would be the output of the following program with the given rainfall data:
2 4 3 0 8 1
#include <iostream>
using namespace std;
main(){int n = 0, max;
int rainfall[10];
while (cin>>rainfall[n]) {n++; }
cout<<"THE RAINFALLS ARE "<<endl;
for ( int i = 0; i < n; i++) cout << "DAY = "<< i+1<<" " <<rainfall[i]<<endl;
max = rainfall[0];
for ( int j = 0; j < n; j++) if (rainfall[j] > max ) max = rainfall[j]; //end loop
cout <<"THE MAX IS "<<max;
return 0;}// end main
Q5h) Write a program that takes in ten numbers, saves them into an array, sorts them, and then displays the numbers in ascending order.
The purpose of this phase is to expand the payroll system to display all employee information in a tabular form by including arrays.
A) Display company title and a header that labels the output in a tabular form. Input the first name and last name of an employee.
char firstname[10], lastname[15];
Hint: You may want to use the following I/O manipulators.
#include <iomanip>, setw(15), setprecision(2) setiosflags(ios::fixed|ios::showpoint|ios::left)
DR. EBRAHIMIS PAYROLL INSTITUTE
106 EASY WAYS
PLEASANTVILLE, N.Y. 11068
FIRST NAME LAST NAME STAT SSN HW HR OTH OTP REGP GROSS TAX NET
=========== ========== === === == === === ==== ==== ====== === ====
JOHN SMITH M 113 50 20 10 300 800 1100 385 715
JANE DOE M 223 45 15 5 112..5 675 787.5 275 512.5
B) Convert the program as it is to arrays. Set maxsize of array to 100.
int hw[100],empid[100];
C) Take advantage of arrays by breaking programs into separate units. Each unit should have a separate loop.
· Read all data into arrays.
· Compute all the overtimepays.
· Compute all the grosspays.
· Compute all the taxrates.
· Compute all the netpays.
· Display all the arrays.
D) Include a search by employee id. (An extra-credit)
E) Include a search by employee name. (An extra-credit)
F) Sort the data either by employee id or by employee name.