MODULE 6: Arrays and Lists
Objectives
By the end of this module, you will be able to:
Understand the concept of a list called array
Manipulate and work with arrays
Know how to pass array into functions
Understand how to handle two-dimensional
array
Use multidimensional array
MODULE 6: Arrays and Lists
UNIT –6.1 Introducing Arrays
UNIT –6.2 Declaring Array Variables
UNIT –6.3 Initializing Array
UNIT –6.4 Manipulating and Processing array
elements
UNIT –6.5 Passing Arrays to Functions
UNIT –6.6 Modifying Arrays in Functions
UNIT –6.7 Two-dimensional Arrays
UNIT –6.8 Multidimensional Arrays
6.1 Introducing Arrays
Array is a data structure that represents a
collection of the same types of data or objects.
E.g. array named myList have ten data of the same
type double is defined as:my List [10];
double
my List[0] 5.6
my List[1] 4.5
my List[2] 3.3
my List[3] 13.2
my List[4] 4.0
Array element at
my List[5] 34.33 Element value
index 5
my List[6] 34.0
my List[7] 45.45
99.993
my List[8]
111.23
my List[9]
Declaring Array Variables
datatype arrayRefVar[arraySize];
Example:
double myList[10];
C++ requires that the array size used to declare an array
must be a constant expression. For example, the following
code is illegal:
int size = 4;
double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
double myList[size]; // Correct
Indexed Variables
The array elements are accessed through the index.
In languages like C/C++/Java, array indices starts
from 0 to arraySize-1. In the example above array
named myList is created to take 10 elements each
of type double. And the indices are from 0 to 9.
Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayName[index];
For example, myList[0] represents the first element
in the array myList while myList[9] represents the
last element in the array myList.
Initializing Array
Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1, ..., valuek};
double myList[4] = {1.9, 2.9, 3.4, 3.5};
//when you already know the values
This shorthand notation is equivalent to the following
statements:
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Array…
Using this notation, you have to declare, create, and
initialize the array all in one statement. Splitting it would
cause a syntax error. For example, the following is wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
Implicit Size
C++ allows you to omit the array size when declaring and
creating an array using an initilizer. For example, it is
acceptable to declare as follows:
double myList[] = {1.9, 2.9, 3.4, 3.5}; //size ommitted
C++ automatically figures out how many elements are in
the array.
Assigning element using loop
int arrayOfNumbers[10]; //declaration
// loop to assign values to all element by adding
2 to I at each loop
for(int i = 0; I < 10; i ++)
arrayOfNumbers[i]= i+2;
// printing some elements
cout<<arrayOfNumbers[2];
cout<<arrayOfNumbers[3];
cout<<arrayOfNumbers[9];
Initializing arrays with random values
The following loop initializes the array myList
with random values between 0 and 99:
for (int i = 0; i < ARRAY_SIZE; i++)
{
myList[i] = rand() % 100; /* rand is a predefined
function to generate random values */
}
TUTOR MARKED ASSESSMENT (TMA)
Assignments/Tasks for the students:
1) Write a code listing to output the content of the following array:
int myArray[] = {3, 5, 6, 9, 3};
2) Write a code listing that will read in array element from the
keyboard
3) What is the output of the following arithmetic operation:
I. 6%8
II. 5%2
Initializing Character Arrays
char zone[] = {'N', 'O', 'R', 'T', 'H'};
char zone[] = "NORTH";
This statement is equivalent to the preceding
statement, except that C++ adds the character '\
0', called the null terminator, to indicate the
end of the string, as shown below. Recall that a
character that begins with the back slash symbol
(\)
'N'
is an escape
'O'
character.
'R' 'T' 'H' '\0'
zone[0] zone[1] zone[2] zone[3] zone[4] zone[5]
Arrangement of characters on array or list memory
Initializing Arrays: More Example
float t[]= {1.0, 3.4, 2.5, 9.0, 7.5, 5.0, 4.0 };
char color[3] = { ‘R’, 'E', ‘D' } ;
char color[4] = "RED”;
char color[] = "RED";
int digits[10] = {1, 2, 3, 4, 5 , 6, 7, 8, 9,
10};
int digits[] = {1, 2, 3, 4, 5 , 6, 7, 8, 9, 10};
Spot the difference especially between the
2nd and the 3rd.
Array further illustration
For one-dimensional array, there will be a single
subscript (sometimes called an index) whose value
refers to individual array elements. If the array
contains n elements, the subscript will be an
integer quantity whose values range from 0 to n-1 .
Note that an n-character string will require an (n+1
)-element array, because of the null character (\
O)that is automatically placed at the end of the
string.
Example using array to store string:
Consider storing string “LAGOS ” in a one-
dimensional character array named state. LAGOS
will be stored in 6 element array as state[6]:
one-dimensional character
array
Element No. Subscript No. Array Data Item
Element (String
Character)
1 0 State[0] L
2 1 State[1] A
3 2 State[2] G
4 3 State[3] O
5 4 State[4] S
6 5 State[5] \0
one-dimensional character
array
L A G O S \0
Subscrip 0 1 2 3 4 5
t:
6 – element character array
Therefore, the 3rd array element is G represented by state[2]
The important thing is that the size allocated must not be less than the
items to be stored
We can read in the value “LAGOS” as follows:
char state[6];
Cin>>state;
The following declaration is also allowed. Here, You don’t have to specify the size:
char state[ ] = “LAGOS”; //acceptable
char state[6 ] = “LAGOS”; // acceptable
char state[5] = “LAGOS”;//this truncates the end of string character
char state[20 ] = “LAGOS”;// too large waste space, extra spaces may be filled with
zeros or meaningless characters
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays Dallas:
char zone[]= " NORTH ";
cout << zone[];
Copying Arrays
int x = 10;
int y;
y = x;
You are not permitted to do this assignment operation in
C++
list = myList; //copying array list into another array as this
Copying into array
You have to copy individual element from one
array to the other as follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i];
}
Summing All Elements
Use a variable named total to store the sum.
Initially total is 0. Add each element in the array
to total using a loop as follows:
int myList[4] = {1, 2, 3, 4};
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total = total + myList[i];
}
Passing Size along with Array
Normally when you pass an array to a function,
you should also pass its size in another argument.
So the function knows how many elements are in
the array. Otherwise, you will have to hard code
this into the function or declare it in a global
variable. Neither is flexible or robust.
6.5 Passing Arrays to Functions
#include <iostream>
using namespace std;
void printArray(int list[], int arraySize); // function prototype
int main()
{
int numbers[5] = {1, 4, 3, 6, 8};
printArray(numbers, 5); //or use numbers.length instead of 5
return 0;
}
void printArray(int list[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout << list[i] << " ";
}
}
Pass-by-Reference: Array
Passing an array variable means that the starting address of the array is passed to
the formal parameter. The parameter inside the function references to the same array
that is passed to the function. No new arrays are created. This is pass-by-reference.
#include <iostream>
using namespace std;
void m(int, int []);
int main(){
int x = 1; // x represents an int value
int y[10]; // y represents an array of int values
y[0] = 1; // Initialize y[0]
m(x, y); // Invoke m with arguments x and y
cout << "x is " << x << endl;
cout << "y[0] is " << y[0] << endl;
return 0;
}
void m(int number, int numbers[])
{
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
TUTOR MARKED ASSESSMENT (TMA)
Assignments/Tasks for the students:
1) Demonstrate an example of array passed by reference using a code
listing example of your choice
2) What is the difference between parameter passed by value and
parameter passed by reference
3) Write out how large an array can be declared for integers, strings and
characters
6.7 Two-dimensional Arrays
If array named “ t [ ]” is used to hold the values of seven
different temperature values in one week. The array index
allows us to loop through the elements of the array(as in t[i])
and reference each element via its index (e.g. t[2]; pointing to
the third element). Assuming we want to process temperatures
for four weeks (i.e. a month). The declaration and memory
allocation below could be used:
double[] t1 = new double [7]; // for week one temperatures
double[] t2 = new double [7]; // for week two temperatures
double[] t3 = new double [7]; // for week three temperatures
double[] t4 = new double [7]; // for week four temperatures
The above means that four different arrays were created
bearing different array names; t1, t2, t3 and t4.
Two-dimensional Arrays
Since there are four different arrays with different names,
it is required to process the array differently. For example,
to enter values into them will require that we run each
through an independent loop. Therefore, it means four
different loops are required to fill all the arrays with
elements. This could be made less tedious by creating a
two-dimensional / multi-dimensional array.
A multi-dimensional array is an array that has more than
one index. It means also if there are 3 indices it becomes
3-dimensional…etc.
A two-dimensional array is a data structure used to
represent a table with rows and columns.
Two-dimensional Arrays
// Declare array reference variable
dataType arrayName[rowSize][columnSize];
int matrix[5][5];
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3]
[0] [0] [0] 1 2 3
[1] [1] [1] 4 5 6
[2] [2] 7 [2] 7 8 9
[3] [3] [3] 10 11 12
[4] [4] int array[][] = {
{1, 2, 3},
int matrix[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare,
create and initialize a two-dimensional array. For
example:
int array[4][3] = { int array[4][3];
{1, 2, 3}, Equivalent array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
(b)
(a)
Initializing Arrays with Random Values
The following loop initializes the array with
random values between 0 and 99:
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < columnSize;
column++)
{
matrix[row][column] = rand() % 100;
}
}
Summing all Elements
To print a two-dimensional array, you have to print
each element in the array using a loop like the
following:
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < columnSize;
column++)
{
Total + = matrix[row][column];
}
}
6.8 Multidimensional Arrays
Occasionally, you will need to represent n-
dimensional data structures. In C++, you can create
n-dimensional arrays for any integer n.
The way to declare two-dimensional array can be
generalized to declare n-dimensional array for n >=
3. For example, the following syntax declares a
three-dimensional array scores.
double scores[10][5][2];
END OF MODULE ASSESSMENT (EMA)
Task to do: Software Application Development
Task (EMA)
1. Write a program that finds the average of
and the read in values (of a set of grades),
store them in an array and then find the
average and display the whole array to the
screen and also display the average to the
screen. It also returns the maximum value
and the minimum value of the array to the
user.
2. write a function that returns the min (hint
use pointers)
void findMin(int *min)
END OF MODULE ASSESSMENT (EMA)
Task to do: Software Application Development
Task (EMA)
3. Marindoti was offered a two-week contractual
terminal appointment to supply oil (in litre) to Dungu
PLC. He made different supplies per day. Write a C++
program using different named functions to
accomplish the following:
Read in daily supplies for the two weeks (use a multi-
dimensional array; there are 7 days in a week)
Compute the cost of daily supply stored in another
array if oil is 155 naira per litre.
Display the cost of all the daily supply in naira
Display the total cost of supplies for the entire period
END OF MODULE ASSESSMENT (EMA)
Task to do: Software Application Development Task (EMA)
4. A magic word square is a square where a word can be formed from
reading each row and each column. For example, the following is a 4 by 4
magic word square:
‘P’ ‘R’ ‘E’ ‘Y’
‘L’ ‘A’ ‘V’ ‘A’
‘O’ ‘V’ ‘E’ ‘R’
‘T’ ‘E’ ‘N’ ‘D’
a)Declare and initialize a 2D array, magicSquare, to hold the
words illustrated above
b)Write a function, displayRow, that accepts the magicSquare
array and a row number and displays the word in that row.
c)Write a function, displayColumn, that accepts the
magicSquare array and column number and displays the word in
that column
d)In a two dimensional array named someArray, what is the