Unit 14:ARRAYS IN C++ PROGRAMMING
Key Unit Competency
By the end of this unit, you should be able to use arrays and strings in a C++ program.Unit Outline
• One-dimensional Arrays.
• Creating one-dimensional Arrays.
• Accessing Array Elements.
• Array of charactersIntroduction
This unit builds on earlier concepts on one-dimensional arrays, variables, data types and control structures. More specifically, this unit demonstrates how to create and manipulate one-dimensional arrays. We start by demonstrating how to create and manipulate one-dimensional array of numeric elements. Later, we demonstrate how to create one-dimensional array of characters also known as strings.14.1 One-dimensional Array
An array is a series of elements having the same name and data type placed in contiguous memory locations. To create an array in C++, you need to consider the following:
• Type of elements: The elements in an array must be of the same type. Some of the valid types stored in an array include primary data types (e.g. int, float, double, and char), and compound types such as string.
• Array size: Because arrays occupy space in memory, you must specify the number of elements beforehand so that the compiler sets aside enough memory space.
• Dimensions: Arrays can have any number of dimensions although it is likely that most of the arrays you create will be of one or two dimensions. To access elements in an array, you must indicate its position using a subscript (index) for each of its dimensions.14.2 Creating One-dimensional Array
In this section, we demonstrate how to create one-dimensional array of ten integers named house. The house array is first initialised to 10 values to be stored in each element.Fig. 4.1 shows a sample output after running the program. Note that the ten elements are listed from 1 to 10.
14.2.1 Declaration of Array
Declaring an array is similar to declaration of simple data types only that square []are used to instruct the computer to reserve enough memory locations to store array
elements. The general syntax of declaring a one-dimensional array is:type array name[number of elements];
Where type refers to data type to be stored in the array, followed by the array name and number of elements. For example, the follow array named house stores 10 elements of integer type:
int house[10];
Once you declare house array, the computer sets aside memory locations (addresses) for storing ten integer values such as 34,20,45,87,92,21,42,56,12 and 15.
Activity 14.1: Declaration of arrays
1. Study the following graphical representations of one-dimensional array and answer the questions that follow:(a) Determine each array name, data type and number of elements stored in each array.
(b) Using C++, write declaration statement that sets the array elements to appropriate data type.
2. A bus has purchased a computer for its new automated reservations system. You are requested to program the new system that assigns seats to passengers for each trip. Using one dimensional arrays, design and write a program in c++ that assigns 30 seats as an array of integers. The output from the program should be the subscript and number, eg:14.2.2 Initialisation of arrays
Array initialization refers to assigning elements to default values at compile time. In C++, elements of an array can be initialised during array declaration by assigning the array to list of comma-separated values enclosed in {}braces. For example, the house array in our example initialises the array as follows:int house[10]={165,150,219,300,220,450,60,80,55,172};
If there are fewer initialisers than the number of elements, the remaining elements are automatically initialised to zero. For example, the elements of the house array could have been initialized to zero as follows:int house[10] = {165,150};
The statement initialises the first two element to 165 and 150, and the remaining eight elements are initialised to two values followed by zeros as follows:
house[10] = {165,150,0,0,0,0,0,0,0,0};It is important to note that, declaration of an array does not automatically initialise elements to zero. To automatically initialise all elements to zero, use empty braces or initialise at least the first element to zero as follows:
int house[10]={0};
If the array size is omitted in the square bracket but elements initialised using comma-separated list of initialisers, the compiler assigns the array size enough to hold the number of elements in the list. For example, the definition below creates a five-element array:
int apartment[ ]={1,2,3,4,5};Activity 14.2: Initialising an array
1. Demonstrate how to initialise an array named product to the following list of
numbers: 21,32,43,54,65,76,87,88,99,200.
2. Explain whether the following array initialisation causes syntax error:
double product[8]={32,27,64,18,95,14};
3. Study the program below and explain line-by-line how the program works to provide desired output.Compare your output with sample screen shown on Fig. 14.2 below:
14.3 Accessing Array Elements
In one-dimensional arrays, each element can be accessed using subscript which is usually an offset of 1 from the number of elements using the following general syntax:
name[n-1];
The subscript n-1 is an offset of n elements because in C++, subscripts counts from 0. For example, to access the fifth element in the house array that has 50 elements, use the following syntax:
house[4];
The most convenient way to access multiple elements of an array is to use the for loop to be demonstrated later. The reason why for loop is desirable is because the number of elements is known beforehand.14.3.1 Reading values into Array Elements
To read values into a specific element of an array , use the following syntax:
cin>>name[n-1];
The statement uses the cin object to accept user input and stores the value into the element specified by n-1 offset. For example, the following statement prompts the user to enter a value that is stored into the fifth element:
cin>>house[4];
Instead of reading one element at a time, you can populate multiple array elements using the for loop. For example, to read multiple values into house array, use the for loop as follows:The program shown above populates the 10 elements of the house array as shown in Fig. 14.3.
The loop intialises the control variable i to zero and loops until it is nine. The cout
statement prints the statement “Please enter house no:”, which is followed by i+1 to
start counting from 1.14.3.2 Writing values from Array Elements
Similar to the syntax of reading values into array elements, you can display a single
value from array using the cout object as follows:
cout<<name[n-1]
For example, the following statement may be used to displays the fifth element from
the house array:
cout<<house[4];
To display multiple values from array elements, use the cout object and the for loop.
For example, the following for loop displays values from the house array:
for(int i=0; i<10;i++){
cout<<i+1<<”:“<<house[i]<< endl;
}
The following program is a modification of the code listing in activity 14.2 to
demonstrate how to read and write values from the array named house:
#include<iostream>
using namespace std;
int main(){
int house[10] = {};//use for loop to read values into house array
for (int i = 0; i<10; i++){
cout<<”Please enter house No:”<<i+1<<endl;
cin>>house[i];
}//end reading
//use for loop to print house array
for (int i = 0; i<10; i++){
cout<< i+1<<”: “<<house[i]<< endl;
}//end printing
return 0;
}Fig. 14.4 shows an illustration of the program after running it. The first part denotes the read operation while the second part displays the values.
Activity 14.3: Reading and writing array elements
Thirty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 5 (1=poor, 2=fair, 3=neutral, 4 =good, and 5=excellent). Write a C++ program that stores 45 responses into one-dimensional array and give a summary of each case in terms of count and percentage.Assessment Exercise 14.1
1. Differentiate between one-dimensional array and multi-dimensional array.
2. Declare a one-dimensional array that represents a 99-element floating point array called cashflow.
3. Assuming the array in 2 above is implemented using C++, what are the first and last elements in the array?
4. The following is a list of numbers representing customers waiting to board a
25-seater bus that serve between Huye and Kigali:64, 25,69, 67, 80 and 85.
(a) Define an array named Passenger initialized to false if a seat is empty.
(b) Write a sample code that initializes to zero all the elements of Passenger array in question 4 above.
(c) Assuming the array is implemented in C++, write a program that would be used to read and display ticket numbers for 25 elements of fully booked bus.
5. Write a C++ program that converts a decimal number to binary form. Store the binary digits in an array and correctly displays the binary number.
6. Study the following code fragments and identify possible errors. In each case, explain the consequences of not correcting the error(s):
a. Assume that: int box[ 10 ] = { };
for ( int i = 0; i <= 10; ++i )
box[ i ] = 1;
Assume that: int ax[ 3 ];
cout << ax[ 1 ] << “ “ << ax[ 2 ] << “ “ << ax[ 3 ];7. Study the following program and give the output produced after running it:
8. Identify and correct syntax error(s) in the following program.
14.4 Array of Characters
To easily handle strings, C++ Standard Library implements string data type that is very useful in handling strings of characters. Because a string is made up of a group of characters, we can also represent them as arrays of char elements using the syntax:
char name[elements];
For example, to declare an array of characters called greetings, use the following syntax:
char Greeting[10];
It is important to note that an array has few characters elements than its size because the last element must store a special character signals end of the string.This special character denoted by ‘\0’ (backslash and zero) is called null character. The program below shows how to create an array of character named Greeting.
#include <iostream>
using namespace std;
int main(){
char Greeting[30];
cout << “Greet someone:”;
cin.get(Greeting, 30); //enter 29 characters
cout << “Greetings:”<<Greeting<< endl;
return 0;
}
Fig. 14.5 shows a sample output after running the program:The program uses cin and get() function separated by a period to read characters and store a string of 29 characters. Note that in this case, the 30th element is reserved for the null terminator \0 that denotes the end of a string.
14.4.1 Initialisation of Strings
Similar to the syntax of initialising array of numbers, we can initialise an array of characters with some predetermined sequence of characters within {} braces as follows:char name[elements]={.,.,.,’\0’};
The dots in this case represents comma-separated characters enclosed in single quotes, and a null character toward the end. For example, the following definition initialises the Greeting array with “hello” string:
char Greeting[6]={`H’,`e’,`l’,`l’,`o’,`\0’};
Note that, although Hello string has five characters, the sixth element is used to hold `\0’ that signals end of the string. However, instead of initialising an array with comma-separated characters in {} braces, you can declare and initializse a string as follows:
char Greeting[ ]=“Hello”;
Note that, the size of Greeting array is determined by “Hello” enclosed in double quotes on the right. This type of initialisation does not require use of a null character because C++ compiler inserts it automatically.Activity 14.4: Initialising strings
Study the following graphical representations of one-dimensional array of characters and answer the questions that follow:1. Determine the array name, data type and number of valid elements stored in the array.
2. Using C++, write declaration statement that assigns the array elements to values shown in the illustration.14.4.2 Reading and Displaying Strings
The cin object consists of special function such as get() used to read a valid sequence of null-terminated characters from the input stream. Normally, cout statement and string library functions may be used to display a string, substring or characters. Like the Greeting array discussed earlier, the following program declares a string called buffer that has a maximum of 79 characters:A sample output after running the program is shown in Fig. 14.6 below
Note that the statement;
cin.get(buffer,79);
means that the get() function of cin object takes two parameters, i.e., the array and number of characters in the array. The array called buffer declared in line 4 is passed in as the first argument while 79 is the second argument that determines the maximum number of characters to be read. In this case, it must be 79 to allow for the null terminator. In addition to functions associated with cin and cout objects, you may also use library functions shown in Table 14.3 below to manipulate strings.The program below demonstrates use of the two library function namely strcpy() and strlen().
Fig. 14.7 shows a sample output from the program that copies and counts the number
of characters in a string.Explanation
1. This program declares and initializes two strings namely String1 and string 2. String1 can hold any number of character because the number of elements is not defined while String2 can hold a string of 80 characters including the null terminator.
2. Once the program is executed, original value of String2, i.e., Promote Peace is displayed. The statement strcpy(String2,String1) replaces the first parameter (String2) with e second parameter (String1), hence replacing “Promote Peace” with “Love your neighbour”.
3. The new value after replacing original String2 with String1 is displayed as shown in Fig. 14.8
4. The strlen() function returns the total number of character i.e 19 including spaces in String2.Activity 14.5: String functions
• Identify C++ library functions used to manipulate strings such as counting number of characters, concatenating and copying.
• Write a program that uses string concatenation function to combine greetings and your name strings.Assessment Exercise 14.2
1. Explain the purpose of null character ‘\0’ in regard to array of characters.
2. Declare a one-dimensional array of characters that would be used to store names of major towns and cities in Rwanda.
3. Assuming the array in 2 above is implemented using C++, represent graphically how a string “Cyangugu” will be stored in the array of characters.
4. The following is a list of numbers representing customers waiting to be served in a banks: Ann, Ben,Helen, Paul, Joy and Ken. Create an array named Customers initialized using the names.
5. Write a program that would be used in reading and writing the elements into an array.
6. Differentiate between the following string initialization statements:char greet[ ]={‘H’,‘e’,‘l’,‘l’,‘o’,‘\0’};
char greet[ ]=“Hello”;Unit Test 14
1. Differentiate between array declaration and array initialization.
2. Explain at least two reasons that would necessitate the use of for loop in onedimensional
arrays.
3. State three factors you would considered when creating a one-dimensional array.
4. In C++, it is possible to read and display elements past the end of the array. How
can such a bug be detected and corrected?
5. Explain why storage of characters array is different from storage of numeric
elements in an array.
6. Differentiate between a null character and null value as used in arrays.
7. Using a sample program, demonstrate how you would use the get() function to
read a string in as an array of characters. The output from the program should be
displayed on the screen.
8. Differentiate between strcpy () and strncpy() library functions used to manipulate
strings.9. Write a c++ program that prompts the usr to enter his or her last name. the program should then display the name and the number of characters that makes up that name.
10. The figure below shows faces of six-sided die with each side marked with dots representing each face 1. To generate random numbers, a player rolls a single die 600 times and the frequency of each face is recorded in an array. Write a C++ program that would be used to output frequency of each face in a one-dimensional array.11. Give the output produced by the following program:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char msg [ ]= “Hello World!”;
char msg1[ ] =”Computer Science”;
string msg2;
cout << msg << endl;
cout << strlen(msg) << endl;
cout << msg1[3] << endl;
msg2= strcat(msg,msg1);
cout << msg2 << endl;
cout << strcat(msg1, “ Study”) << endl;
} //end main