CHAPTER 5

 

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].

Text Box: 1.       #include<iostream>
2.      using namespace std;
3.       main(){
4.            int x;
5.            x = 5;
6.            x = 10;
7.            cout << “X WAS ” << x<<endl
8.                    << “X IS ” << x << endl;
9.            return 0;
10.   }//MAIN
 
Text Box: Figure 5.1a – Illustrates the use of a single value x variable, non-array based, to store two numbers.
Text Box: X WAS 10  
X IS 10
Text Box: X WAS 5  
X IS 10
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
Text Box: Figure 5.1b – Illustrates the use of an array variable named x which can store two numbers.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 5.1c – Output of Figure 5.1a.  Notice that the original value of x, the value of 5, is overwritten with the new value of x, which is 10. 
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.

  

 

 

 


 

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 ARRAY–PAYROLL PROGRAM

For the moment, look at this program and the task is to convert this program to its array-based version.   

Text Box: 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.  }//MAIN

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 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.


 

 

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
 
 
Text Box: Figure 5.2b – A version of the Payroll Program using arrays.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: 1645      41        18.10
8932      40         20.00
7104      60         15.99
2816      25         50.00
5387      30         16.99

  

 

 

 

 

 

Text Box: Figure 5.2c  -- Input File named payroll.in used for the programs of Figure 5.2a and Figure 5.2b.

  

 

 

 

 

 

 

 

 

 

Text Box:  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.7

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 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:

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
 
            
 

  

 

 

 

 

 

 


 

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.       

 

 

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.

Text Box: Figure 5.3b –(left) File named numbers.in is used to read load the array element tbl.
Text Box: 1
2
3
4
5
6
7
8
9
10
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
 
Text Box: Figure 5.3a – Program illustrates reading data into an array and then accessing the first, middle and last elements of the array.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 5.3c – The output of the program of Figure 5.3a.
Text Box: FIRST ELEMENT   1
MIDDLE ELEMENT  6
LAST ELEMENT    10
 

 

 

 

 

 

 

 

 

 


 

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.

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

  

 

 

 

 

 

 

 

 

 

Text Box: Figure 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.
Text Box: 10
20
30
40
50
Text Box: 11
22
33
44
55
 

 

 

 

 

 

Text Box: Figure 5.4b – File named numbers2.in that is used to load the array element tbl of Figure 5.4a.
 
Text Box: Figure 5.4c – Output of the program listed in Figure 5.4a using the data file of Figure 5.4b.
 

  

 

 

 

 

 

 

 

 

 

 


 

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. 

 

for( intialvariable ;  testvariable ;  updatevariable ) { // body of the loop; }

 

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
Text Box: Figure 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.


 

 

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
Text Box: Figure 5.6a – The program sums all numbers that read into the array named num.
Text Box: Figure 5.6b – The output of Figure 5.6a using the input file named numbers.in.
Text Box: THE SUM OF THE NUMBERS IS 55
 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

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 ];

 

Text Box: Table 5.1 – Summation of array elements.

 

 

 

 

 

 

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 )

 

Text Box: Table 5.2 – Sample declarations of character arrays.

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
Text Box: Figure 5.7a – Entering a name character by character.
Text Box: abcdefghijklmno
NAME IS abcdefghijklmno

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 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.


 

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
Text Box: Figure 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.

 

 

                                                              INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

               
           
Hosted by www.Geocities.ws

1