0% found this document useful (0 votes)
172 views19 pages

CC103 Mod4

The document is a study guide for a programming module on arrays. It discusses: 1) How arrays allow grouping of related variables of the same type in contiguous memory locations accessed via indices. 2) How to declare, initialize, and access values in one-dimensional arrays. Arrays can be initialized with a list of values. 3) Examples of valid array operations like assignment, accessing elements, and performing calculations with element values.

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views19 pages

CC103 Mod4

The document is a study guide for a programming module on arrays. It discusses: 1) How arrays allow grouping of related variables of the same type in contiguous memory locations accessed via indices. 2) How to declare, initialize, and access values in one-dimensional arrays. Arrays can be initialized with a list of values. 3) Examples of valid array operations like assignment, accessing elements, and performing calculations with element values.

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

FM-AA-CIA-15 Rev.

0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

STUDY GUIDE FOR MODULE NO. 4

ARRAYS
MODULE OVERVIEW

The previous modules discussed how grouping related statements into one name through function declaration
and definition makes it easy for programmers to break down a large problem into manageable tasks. The
concept of grouping can also be applied to variables. All of the variables we have used so far are simple
variables that are unrelated to any other variable in memory. However, some programs will require the use of
variables that are related to each other to make it easier and more efficient to treat the related variables as a
group. To do this, we group together related variables that have the same data type, which is referred to as an
array of variables or, more simply, an array. You will learn in this module how the variables in an array can be
used just like any other variables. You can assign values to them, use them in calculations, display their
contents, and so on.

MODULE LEARNING OBJECTIVES

By the end of this module, you should be able to:


 Declare and initialize a one-dimensional array.
 Implement a one-dimensional array in solving a problem.
 Understand the structure of a two-dimensional array.
 Implement a multidimensional array in solving a problem.

LEARNING CONTENTS (PARAMETER PASSING MECHANISMS)

Introduction
An array is a collection of variables of the same type that are referred to by a common name. Arrays may
have from one to several dimensions, although the one-dimensional array is the most common. Arrays offer a
convenient means of creating lists of related variables. The array that you will probably use most often is the
character array, because it is used to hold a character string. The C++ language does not define a built-in
string data type. Instead, strings are implemented as arrays of characters. This approach to strings allows
greater power and flexibility than are available in languages that use a distinct string type.

4. Array
An array is a series of elements of the same type placed in contiguous memory locations that can be
individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.

For example, an array to contain 5 integer values of type int called my_array could be represented like
this:

PANGASINAN STATE UNIVERSITY 1


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

where each blank panel represents an element of the array, that in this case are integer values of type int.
These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its
length.

Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++
is:

type name [elements];

where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always
enclosed in square brackets []), specifies how many of these elements the array has to contain.

Therefore, in order to declare an array called my_array as the one shown in the above diagram it is as
simple as:

int my_array[5];

NOTE: The elements field within brackets [] which represents the number of elements the array is going to
hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be
determined before execution. In order to create arrays with a variable length dynamic memory is needed.

4.1 Initializing arrays


When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise,
its elements will not be initialized to any value by default, so their content will be undetermined until we store
some value in them. The elements of global and static arrays, on the other hand, are automatically initialized
with their default values, which for all fundamental types this means they are filled with zeros.

In both cases, local and global, when we declare an array, we have the possibility to assign initial values to
each one of its elements by enclosing the values in braces { }. For example:

int my_array[5]={ 25, 32, 80, 100, 1250};

This declaration would have created an array like this:

The amount of values between braces { } must not be larger than the number of elements that we declare for
the array between square brackets [ ]. For example, in the example of array my_array we have declared that
it has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each
element.

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of
values included between braces { }:

int my_array[10]={ 25, 32, 80, 100, 1250, 35678};

After this declaration, array my_array would be 5 integers long, since we have provided 5 initialization
values.

4.2 Accessing the values of arrays


In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value. The format is as
simple as:

PANGASINAN STATE UNIVERSITY 2


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

name[index]

Following the previous examples in which my_array had 5 elements and each of those elements was of
type int, the name which we can use to refer to each element is the following:

For example, to store the value 75 in the third element of my_array, we could write the following statement:

my_array[2] = 75;

and, for example, to pass the value of the third element of my_array to a variable called a, we could write:

a = my_array[2];

Therefore, the expression my_array[2]is for all purposes like a variable of type int.

Notice that the third element of my_array is specified my_array[2], since the first one is my_array[0],
the second one is my_array[1], and therefore, the third one is my_array[2]. By this same reason, its last
element is my_array[4]. Therefore, if we write my_array[5], we would be accessing the sixth element
of my_array and therefore exceeding the size of the array.

In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems,
since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The
reason why this is allowed will be seen further ahead when we begin to use pointers.

At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related
to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and
the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of
brackets [ ] with arrays.

int my_array[5]; //declaration of a new array


my_array[2]=75; //access to an element of the array

If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it
never precedes an access.

Some other valid operations with arrays:

int my_array[]= {1, 45, 89, 5, 87, 23, 100, 4, 5, 33, 23 45, 90};

my_array[0]= a;

my_array[a] =75;
b= my_array[a+2];
my_array[8] =5;

my_array[my_array[a]] = my_array[2] + 5;

PANGASINAN STATE UNIVERSITY 3


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

To see how the valid operations work, let us take a look at the code below:

#include <iostream>
using namespace std;

int main()
{
int a=8;
int b;
int my_array[]= {1, 45, 89, 5, 87, 23, 100, 4, 5, 33, 23, 45, 90};
cout<<"Initial array elements: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}
my_array[0]= a;
my_array[a] =75;
cout<<"\n The value of index 8 is "<<my_array[a];
b= my_array[a+2];
cout<<"\n The value of variable b is: "<<b;
my_array[8] =5;
cout<<"\n after assignments of values: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}

my_array[my_array[a]] = my_array[2] + 5;
cout<<"\n The value of index 5 is: "<<my_array[5];
cout<<"\n After the code in line 32 was executed: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}
b=my_array[13];
cout<<b;
return 0;
}

Take a look at another example:


1 // arrays example 12206
2 #include <iostream>
3 using namespace std;
4
5 int my_array [] = {16, 2, 77, 40, 12071};
6 int n, result=0;
7
8 int main ()
9{
10 for ( n=0 ; n<5 ; n++ )
11 {
12 result += my_array[n];
13 }
14 cout << result;
15 return 0;
16 }

4.3 Character Sequences


As you may already know, the C++ Standard Library implements a powerful string class, which is very useful
to handle and manipulate strings of characters. However, because strings are in fact sequences of characters,
we can represent them also as plain arrays of char elements.

PANGASINAN STATE UNIVERSITY 4


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

For example, the following array:

char jenny [20];

is an array that can store up to 20 elements of type char. It can be represented as:

Therefore, in this array, in theory, we can store sequences of characters up to 20 characters long. But we can
also store shorter sequences. For example, jenny could store at some point in a program either the
sequence "Hello" or the sequence "Merry Christmas", since both are shorter than 20 characters.

Therefore, since the array of characters can store shorter sequences than its total length, a special character
is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\
0'(backslash, zero).

Our array of 20 elements of type char, called jenny, can be represented storing the characters
sequences "Hello" and "Merry Christmas" as:

Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the
sequence. The panels in gray color represent char elements with undetermined values.

4.4 Initialization of null-terminated character sequences


Because arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to
initialize an array of characters with some predetermined sequence of characters we can do it just like any
other array:

char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

In this case we would have declared an array of 6 elements of type char initialized with the characters that
form the word "Hello" plus a null character '\0' at the end.
But arrays of char elements have an additional method to initialize their values: using string literals.

In the expressions we have used in some examples, constants that represent entire strings of characters have
already showed up several times. These are specified enclosing the text to become a string literal between
double quotes ("). For example:

"the result is: "

is a constant string literal that we have probably used already.

Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters. So
string literals enclosed between double quotes always have a null character ('\0') automatically appended at
the end.

PANGASINAN STATE UNIVERSITY 5


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

Therefore we can initialize the array of char elements called myword with a null-terminated sequence of
characters by either one of these two methods:

1 char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' };


2 char myword [] = "Hello";
In both cases the array of characters myword is declared with a size of 6 elements of type char: the 5
characters that compose the word "Hello" plus a final null character ('\0') which specifies the end of the
sequence and that, in the second case, when using double quotes (") it is appended automatically.

Notice that we are talking about initializing an array of characters in the moment it is being declared, and not
about assigning values to them once they have already been declared. In fact because this type of null-
terminated arrays of characters are regular arrays we have the same restrictions that we have with any other
array, so we are not able to copy blocks of data with an assignment operation.

Assuming mystext is a char[] variable, expressions within a source code like:

1 mystext = "Hello";
2 mystext[] = "Hello";

would not be valid, like neither would be:

mystext = { 'H', 'e', 'l', 'l', 'o', '\0' };

The reason for this may become more comprehensible once you know a bit more about pointers, since then it
will be clarified that an array is in fact a constant pointer pointing to a block of memory.

4.5 Using null-terminated sequences of characters


Null-terminated sequences of characters are the natural way of treating strings in C++, so they can be used
as such in many procedures. In fact, regular string literals have this type (char[]) and can also be used in most
cases.
For example, cin and cout support null-terminated sequences as valid containers for sequences of characters,
so they can be used directly to extract strings of characters from cin or to insert them into cout. For example:

As you can see, we have declared three arrays of char elements. The first two were initialized with string
literal constants, while the third one was left uninitialized. In any case, we have to specify the size of the array:
in the first two (question and greeting) the size was implicitly defined by the length of the literal constant they
were initialized to. While for yourname we have explicitly specified that it has a size of 80 chars.

Finally, sequences of characters stored in char arrays can easily be converted into string objects just by using
the assignment operator:

1 string mystring;
2 char myntcs[]="some text";
3 mystring = myntcs;

Reading a String form the Keyboard


The easiest way to read a string entered from the keyboard is to use a char array in a cin statement. For
example, the following program reads a string entered by the user:

PANGASINAN STATE UNIVERSITY 6


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

Although this program is technically correct, it will not always work the way that you expect. To see why, run
the program and try entering the string “This is a test”. Here is what you will see:
Enter a string: This is a test
Here is your string: This

When the program redisplays your string, it shows only the word “This”, not the entire sentence. The reason
for this is that the C++ I/O system stops reading a string when the first whitespace character is encountered.
Whitespace characters include spaces, tabs, and newlines.

One way to solve the whitespace problem is to use another of C++’s library functions, gets(). The general form
of a call to gets() is
gets(array-name);

To read a string, call gets() with the name of the array, without any index, as its argument. Upon return from
gets(), the array will hold the string input from the keyboard. The gets() function will continue to read
characters, including whitespace, until you enter a carriage return. The header used by gets() is <cstdio>.
This version of the preceding program uses gets() to allow the entry of strings containing spaces:

PANGASINAN STATE UNIVERSITY 7


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

Now, spaces are read and included in the string. One other point: Notice that in a cout statement, str can be
used directly. In general, the name of the character array that holds a string can be used any place that a
string constant can be used.

Keep in mind that neither cin nor gets() performs any bounds checking on the array that receives input.
Therefore, if the user enters a string longer than the size of the array, the array will be overwritten.

4.6 Multidimensional Array


C++ allows arrays with more than two dimensions. Here is the general form of a multidimensional
array declaration:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a 4×10×3–integer array:

int multidim[4][10][3];

Arrays of more than three dimensions are not often used, due to the amount of memory required to
hold them. Remember, storage for all array elements is allocated during the entire lifetime of an array. When
multidimensional arrays are used, large amounts of memory can be consumed. For example, a four-
dimensional character array with dimensions 10,6,9,4 would require 10×6×9×4 (or 2,160) bytes. If each array
dimension is increased by a factor of 10 each (that is, 100×60×90×40), then the memory required for the array
increases to 21,600,000 bytes! As you can see, large multidimensional arrays may cause a shortage of
memory for other parts of your program. Thus, a program with arrays of more than two or three dimensions
may find itself quickly out of memory!

Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be
imagined as a bidimensional table made of elements, all of them of a same uniform data type.

PANGASINAN STATE UNIVERSITY 8


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++
would be:

int jimmy [3][5];

float my_array[63][14];

and, for example, the way to reference the second element vertically and fourth horizontally in an expression
would be:

jimmy[1][3]

(remember that array indices always begin by zero).

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many
indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each
dimension. For example:

char century [100][365][24][60][60];

declares an array with a char element for each second in a century, that is more than 3 billion chars. So this
declaration would consume more than 3 gigabytes of memory!

Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a
simple array just by putting a factor between its indices:

1 int jimmy [3][5]; // is equivalent to


2 int jimmy [15]; // (3 * 5 = 15)

With the only difference that with multidimensional arrays the compiler remembers the depth of each
imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result.
One uses a bidimensional array and the other one uses a simple array:

multidimensional array pseudo-multidimensional array


#define WIDTH 5 #define WIDTH 5
#define HEIGHT 3 #define HEIGHT 3

int jimmy [HEIGHT][WIDTH]; int jimmy [HEIGHT * WIDTH];


int n,m; int n,m;

PANGASINAN STATE UNIVERSITY 9


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

int main () int main ()


{ {
for (n=0;n<HEIGHT;n++) for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++) for (m=0;m<WIDTH;m++)
{ {
jimmy[n][m]=(n+1)*(m+1); jimmy[n*WIDTH+m]=(n+1)*(m+1);
} }
return 0; return 0;
} }

None of the two source codes above produce any output on the screen, but both assign values to the memory
block called jimmy in the following way:

We have used "defined constants" (#define) to simplify possible future modifications of the program. For
example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by
changing the line:

#define HEIGHT 3

to:
#define HEIGHT 4

with no need to make any other modifications to the program.

4.7 Multidimensional Array Initialization


Like a normal array, we can initialize a multidimensional array in more than one way.

4.7.1 Initialization of two-dimensional array


int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same array elements is given
below:
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};

This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.

PANGASINAN STATE UNIVERSITY 10


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

4.7.2 Initialization of three-dimensional array


int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

This is not a good way of initializing a three-dimensional array. A better way to initialize this array is:
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};

Notice the dimensions of this three-dimensional array. The first dimension has the value 2. So, the two
elements comprising the first dimension are:
Element 1 = { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }
Element 2 = { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }

The second dimension has the value 3. Notice that each of the elements of the first dimension has three
elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
{13, 4, 56, 3}, {5, 9, 3, 5} and {5, 1, 4, 9} for Element 2.

Finally, there are four int numbers inside each of the elements of the second dimension:
{3, 4, 2, 3}
{0, -3, 9, 11}
... .. ...
... .. ...

Example 1: Two Dimensional Array


// C++ Program to display all elements
// of an initialised two dimensional array

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};

// use of nested for loop

PANGASINAN STATE UNIVERSITY 11


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

// access rows of the array


for (int i = 0; i < 3; ++i) {

// access columns of the array


for (int j = 0; j < 2; ++j) {
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}

Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

In the above example, we have initialized a two-dimensional int array named test that has 3 "rows" and 2
"columns".
Here, we have used the nested for loop to display the array elements.
 the outer loop from i == 0 to i == 2 access the rows of the array
 the inner loop from j == 0 to j == 1 access the columns of the array

Finally, we print the array elements in each iteration.

Example 2: Taking Input for Two Dimensional Array


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {

PANGASINAN STATE UNIVERSITY 12


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

cin >> numbers[i][j];


}
}

cout << "The numbers are: " << endl;

// Printing array elements


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}

return 0;
}

Output
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6

Here, we have used a nested for loop to take the input of the 2d array. Once all the input has been taken, we
have used another nested for loop to print the array members.

Example 3: Three Dimensional Array


// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream>

PANGASINAN STATE UNIVERSITY 13


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

using namespace std;

int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2}, [0] [0][0], [0][0][1]
{3, 4}, [0] [1][0], [0] [1][1]
{5, 6} [0] [2][0], [0] [2][1]
},
{
{7, 8}, [1] [0][0], [1][0][1]
{9, 10}, [1][1][0], [1][1][1]
{11, 12} [1][2][0], [1][2][1]
}
};

// Displaying the values with proper index.


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
}
}
}

return 0;
}

Output
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9

PANGASINAN STATE UNIVERSITY 14


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

The basic concept of printing elements of a 3d array is similar to that of a 2d array.


However, since we are manipulating 3 dimensions, we use a nested for loop with 3 total loops instead of just
2:
 the outer loop from i == 0 to i == 1 accesses the first dimension of the array
 the middle loop from j == 0 to j == 2 accesses the second dimension of the array
 the innermost loop from k == 0 to k == 1 accesses the third dimension of the array

As we can see, the complexity of the array increases exponentially with the increase in dimensions.

4.7 Arrays as function parameters


At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass
a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In
practice this has almost the same effect and it is a much faster and more efficient operation.

The syntax for passing an array to a function is:

returnType functionName(dataType arrayName[arraySize]) {


// code
}

In order to accept arrays as parameters the only thing that we have to do when declaring the function is to
specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For
example, the following function:

void procedure (int arg[])

accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:

int myarray [40];

it would be enough to write a call like this:

procedure (myarray);

Here you have a complete example:

1 // arrays as parameters 5 10 15
2 #include <iostream> 2 4 6 8 10
3 using namespace std;
4
5 void printarray (int arg[], int length) {
6 for (int n=0; n<length; n++)
7 cout << arg[n] << " ";
8 cout << "\n";

PANGASINAN STATE UNIVERSITY 15


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

9}
10
11 int main ()
12 {
13 int firstarray[] = {5, 10, 15};
14 int secondarray[] = {2, 4, 6, 8, 10};
15 printarray (firstarray,3);
16 printarray (secondarray,5);
17 return 0;
18 }

The first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that
reason we have included a second parameter that tells the function the length of each array that we pass to it
as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the
passed array without going out of range.

In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional
array parameter is:

base_type[][depth][depth]

for example, a function with a multidimensional array as argument could be:

void procedure (int myarray[][3][4])

Notice that the first brackets [] are left empty while the following ones specify sizes for their respective
dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional
dimension.

Example: Passing Multidimensional Arrays as Parameters

PANGASINAN STATE UNIVERSITY 16


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

Output:
Displaying Values:
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1

In the above program, we have defined a function named display(). The function takes a two dimensional
array, int n[][2] as its argument and prints the elements of the array.
While calling the function, we only pass the name of the two dimensional array as the function
argument display(num).
Note: It is not mandatory to specify the number of rows in the array. However, the number of columns should
always be specified. This is why we have used int n[][2].
We can also pass arrays with more than 2 dimensions as a function argument.

Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors
for novice programmers.

LEARNING ACTIVITY 3

Answer the following:

1. What is a one-dimensional array?


2. Does C++ provide bounds checking on arrays?
3. Write the following declarations.
a. An array called topTenList, of 10 values of type string.

PANGASINAN STATE UNIVERSITY 17


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4

b. A two-dimensional array representing the days on a calendar page that may contain a
maximum of 6 weeks. Call the array weeks, and declare an enumeration type consisting of
the names of the days, which can be used to index the array columns. The weeks should be
indexed by an int.
c. Write a declaration of a named array type, and then declare three arrays of that type. The
array type should be called DataSet, and the three arrays should be called input, output, and
working. Each array should hold five float values.
4. Each dimension in a multidimensional array is specified with its own set of brackets. True or False?
5. Show how to declare a two-dimensional integer array called list with the dimensions 4x9.
6. Given list from the preceding question, show how to access element 2,3.
7. What is a null-terminated string?
8. To hold a string that is 8 characters long, how long must the character array be?
9. What function can be used to read a string containing spaces from the keyboard?

Case Study:
1. A piano is tuned in a scale that is slightly unequal (called a “well-tempered scale”), rather than a
perfectly scientific scale in which each note sounds at twice the frequency of the same note an octave
below (called a “just scale”). For this reason, we can’t simply calculate the frequency of a note, but
rather must keep it in a table. Declare a two-dimensional array (scale) to hold the frequencies of the
well-tempered scale. Afrequency is represented by a float value.
2. Write a program to play a game in which you try to sink a fleet of five navy vessels by guessing their
locations on a grid. The program uses random numbers to position its ships on a 15 x 15 grid. The
ships are of different lengths as follows:
Frigate: 2 locations
Tender: 2 locations
Destroyer: 3 locations
Cruiser: 3 locations
Carrier: 4 locations
The program must pick one square as the starting location, then pick the direction of the ship on the
board, and mark off the number of squares in that direction to represent the size of the ship. It must
not allow a ship to overlap with another ship, or to run off the board. The user enters coordinates in
the range of 1 through 15 for the rows and A through O for the columns. The program checks this
location, and reports whether the guess is a hit or a miss. If it is a hit, the program also checks
whether the ship has been hit in every location that it occupies. If so, the ship is reported as sunk, and
the program will terminate.

SUMMARY

Programmers use arrays to temporarily store related data in the computer’s internal memory. Using an array,
a programmer can increase the efficiency of a program since the data can be stored and retrieved much
faster. Further, the program can use the data stored in an array as many time as it is needed after it has been
entered. Each of the array elements that are stored in a one-dimensional array is assigned a unique index
number wherein the first element is assigned the index 0 and the last index is always assigned as one number
less than the number of elements. To access the elements in a one-dimensional array, we specify the array’s
name and the element’s index inside a square bracket. A two-dimensional array resembles a table in that the
elements are in rows and columns. You can determine the number of elements in a two-dimensional array by
multiplying the number of its rows by the number of its columns. Contrary to one-dimensional arrays, two-
dimensional arrays are identified by a unique combination of two indices. The first index represents the
element’s row location in an array, and the second index represents it column location. To refer to each
element in a two-dimensional array by the array’s name and the element’s indices, which are specified in two
sets of square brackets immediately following the name.

REFERENCES

[1] cplusplus.com. Arrays. Retrieved March 15, 2021 from


http://www.cplusplus.com/doc/tutorial/arrays/

[2] Dale, Nell; Weems, Chip; and Headington, Mark. (2001). Programming in C++, 2 nd Edition.

PANGASINAN STATE UNIVERSITY 18


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in CC 103 Intermediate Programming Module No. 4


Jones and Bartlett Publishers, Inc.

[3] Schildt, Herbert (2005). C++ A Beginner’s Guide Second Edition.Corel Ventura Publishers

Online Reading Materials:

 https://www.programiz.com/cpp-programming/arrays
 https://www.programiz.com/cpp-programming/multidimensional-arrays
 https://www.programiz.com/cpp-programming/passing-arrays-function
 https://www.programiz.com/cpp-programming/pointers-arrays
 https://www.tutorialspoint.com/cplusplus/cpp_arrays.htm
 https://www.cplusplus.com/doc/tutorial/arrays/
 https://www.javatpoint.com/cpp-arrays
 https://beginnersbook.com/2017/08/cpp-arrays/

PANGASINAN STATE UNIVERSITY 19

You might also like