Anda di halaman 1dari 29

Arrays

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, five values of type int can be declared as an array without having
to declare 5 different variables (each with its own identifier). Instead, using an array, the five int
values are stored in contiguous memory locations, and all five can be accessed using the same
identifier, with the proper index.

For example, an array containing 5 integer values of type int called foo could be represented as:

where each blank panel represents an element of the array. In this case, these are values of type
int. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the first
element in an array is always numbered with a zero (not a one), no matter 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 (such as int, float...), name is a valid identifier and the elements
field (which is always enclosed in square brackets []), specifies the length of the array in terms
of the number of elements.

Therefore, the foo array, with five elements of type int, can be declared as:

int foo [5];

NOTE: The elements field within square brackets [], representing the number of elements in the array,
must be a constant expression, since arrays are blocks of static memory whose size must be
determined at compile time, before the program runs.

Initializing arrays
By default, regular arrays of local scope (for example, those declared within a function) are left
uninitialized. This means that none of its elements are set to any particular value; their contents are
undetermined at the point the array is declared.

But the elements in an array can be explicitly initialized to specific values when it is declared, by
enclosing those initial values in braces {}. For example:

int foo [5] = { 16, 2, 77, 40, 12071 };


This statement declares an array that can be represented like this:

The number of values between braces {} shall not be greater than the number of elements in the
array. For example, in the example above, foo was declared having 5 elements (as specified by the
number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for each
element. If declared with less, the remaining elements are set to their default values (which for
fundamental types, means they are filled with zeroes). For example:

int bar [5] = { 10, 20, 30 };

Will create an array like this:

The initializer can even have no values, just the braces:

int baz [5] = { };

This creates an array of five int values, each initialized with a value of zero:

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 automatically a size for the array that
matches the number of values included between the braces {}:

int foo [] = { 16, 2, 77, 40, 12071 };

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

Finally, the evolution of C++ has led to the adoption of universal initialization also for arrays.
Therefore, there is no longer need for the equal sign between the declaration and the initializer. Both
these statements are equivalent:

1 int foo[] = { 10, 20, 30 };


2 int foo[] { 10, 20, 30 };

Static arrays, and those declared directly in a namespace (outside any function), are always initialized.
If no explicit initializer is specified, all the elements are default-initialized (with zeroes, for
fundamental types).

Accessing the values of an array


The values of any of the elements in an array can be accessed just like the value of a regular variable of
the same type. The syntax is:

name[index]
Following the previous examples in which foo had 5 elements and each of those elements was of type
int, the name which can be used to refer to each element is the following:

For example, the following statement stores the value 75 in the third element of foo:

foo [2] = 75;

and, for example, the following copies the value of the third element of foo to a variable called x:

x = foo[2];

Therefore, the expression foo[2] is itself a variable of type int.

Notice that the third element of foo is specified foo[2], since the first one is foo[0], the second one
is foo[1], and therefore, the third one is foo[2]. By this same reason, its last element is foo[4].
Therefore, if we write foo[5], we would be accessing the sixth element of foo, and therefore actually
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 errors on compilation, but can cause
errors on runtime. The reason for this being allowed will be seen in a later chapter when pointers are
introduced.
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 when they are accessed.
Do not confuse these two possible uses of brackets [] with arrays.

1 int foo[5]; // declaration of a new array


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

The main difference is that the declaration is preceded by the type of the elements, while the access is
not.

Some other valid operations with arrays:

1 foo[0] = a;
2 foo[a] = 75;
3 b = foo [a+2];
4 foo[foo[a]] = foo[2] + 5;

For example:

1 // arrays example 12206 Edi


2 #include <iostream> &
3 using namespace std; Run
4
5 int foo [] = {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 += foo[n];
13 }
14 cout << result;
return 0;
15
}
16

Multidimensional arrays
Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can
be imagined as a two-dimensional table made of elements, all of them of a same uniform data type.
jimmy represents a bidimensional array of 3 per 5 elements of type int. The C++ syntax for this is:

int jimmy [3][5];

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 with zero).

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

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

declares an array with an element of type char for each second in a century. This amounts to more than
3 billion char! So this declaration would consume more than 3 gigabytes of memory!

At the end, multidimensional arrays are just an abstraction for programmers, since the same results can
be achieved with a simple array, by multiplying 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 automatically remembers the
depth of each imaginary dimension. The following two pieces of code produce the exact same result, but
one uses a bidimensional array while the other 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;

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);
} }
} }

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

Note that the code uses defined constants for the width and height, instead of using directly their
numerical values. This gives the code a better readability, and allows changes in the code to be made
easily in one place.

Arrays as parameters
At some point, we may need to pass an array to a function as a parameter. In C++, it is not possible to
pass the entire block of memory represented by an array to a function directly as an argument. But what
can be passed instead is its address. In practice, this has almost the same effect, and it is a much faster
and more efficient operation.

To accept an array as parameter for a function, the parameters can be declared as the array type, but
with empty brackets, omitting the actual size of the array. For example:
void procedure (int arg[])

This function 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 Edi


2 #include <iostream> 2 4 6 8 10 &
3 using namespace std; Run
4
5 void printarray (int arg[], int length) {
6 for (int n=0; n<length; ++n)
7 cout << arg[n] << ' ';
8 cout << '\n';
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 }

In the code above, 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 array passed, 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.

In a way, passing an array as argument always loses a dimension. The reason behind is that, for historical
reasons, arrays cannot be directly copied, and thus what is really passed is a pointer. This is a common
source of errors for novice programmers. Although a clear understanding of pointers, explained in a
coming chapter, helps a lot.

Library arrays
The arrays explained above are directly implemented as a language feature, inherited from the C
language. They are a great feature, but by restricting its copy and easily decay into pointers, they
probably suffer from an excess of optimization.

To overcome some of these issues with language built-in arrays, C++ provides an alternative array type
as a standard container. It is a type template (a class template, in fact) defined in header <array>.

Containers are a library feature that falls out of the scope of this tutorial, and thus the class will not be
explained in detail here. Suffice it to say that they operate in a similar way to built-in arrays, except that
they allow being copied (an actually expensive operation that copies the entire block of memory, and
thus to use with care) and decay into pointers only when explicitly told to do so (by means of its
member data).

Just as an example, these are two versions of the same example using the language built-in array
described in this chapter, and the container in the library:

language built-in array container library array

#include <iostream> #include <iostream>


#include <array>
using namespace std; using namespace std;

int main() int main()


{ {
int myarray[3] = {10,20,30}; array<int,3> myarray {10,20,30};

for (int i=0; i<3; ++i) for (int i=0; i<myarray.size(); ++i)
++myarray[i]; ++myarray[i];

for (int elem : myarray) for (int elem : myarray)


cout << elem << '\n'; cout << elem << '\n';
} }

As you can see, both kinds of arrays use the same syntax to access its elements: myarray[i]. Other
than that, the main differences lay on the declaration of the array, and the inclusion of an additional
header for the library array. Notice also how it is easy to access the size of the library array.
Two-dimensional Arrays

TWO-DIMENSIONAL ARRAYS were introduced in Subsection 3.8.5, but we haven't done


much with them since then. A 2D array has a type such as int[][] or String[][], with two pairs of
square brackets. The elements of a 2D array are arranged in rows and columns, and the new
operator for 2D arrays specifies both the number of rows and the number of columns. For
example,

int[][] A;
A = new int[3][4];

This creates a 2D array of int that has 12 elements arranged in 3 rows and 4 columns. Although I
haven't mentioned it, there are initializers for 2D arrays. For example, this statement creates the
3-by-4 array that is shown in the picture below:

int[][] A = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, -9 }
};

An array initializer for a 2D array contains the rows of A, separated by commas and enclosed
between braces. Each row, in turn, is a list of values separated by commas and enclosed between
braces. There are also 2D array literals with a similar syntax that can be used anywhere, not just
in declarations. For example,

A = new int[][] { { 1, 0, 12, -1 },


{ 7, -3, 2, 5 },
{ -5, -2, 2, -9 }
};

All of this extends naturally to three-dimensional, four-dimensional, and even higher-


dimensional arrays, but they are not used very often in practice.

7.5.1 The Truth About 2D Arrays


But before we go any farther, there is a little surprise. Java does not actually have two-
dimensional arrays. In a true 2D array, all the elements of the array occupy a continuous block of
memory, but that's not true in Java. The syntax for array types is a clue: For any type BaseType,
we should be able to form the type BaseType[], meaning "array of BaseType." If we use int[] as
the base type, the type that we get is "int[][] meaning "array of int[]" or "array of array of int."
And in fact, that's what happens. The elements in a 2D array of type int[][] are variables of type
int[]. And remember that a variable of type int[] can only hold a pointer to an array of int. So, a
2D array is really an array of pointers, where each pointer can refer to a one-dimensional array.
Those one-dimensional arrays are the rows of the 2D array. A picture will help to explain this.
Consider the 3-by-4 array A defined above.

For the most part, you can ignore the reality and keep the picture of a grid in mind.
Sometimes, though, you will need to remember that each row in the grid is really an array in
itself. These arrays can be referred to as A[0], A[1], and A[2]. Each row is in fact a value of
type int[]. It could, for example, be passed to a subroutine that asks for a parameter of type
int[].

Some of the consequences of this structure are a little subtle. For example, thinking of a 2D
array, A, as an array of arrays, we see that A.length makes sense and is equal to the number of
rows of A. If A has the usual shape for a 2D array, then the number of columns in A would be the
same as the number of elements in the first row, that is, A[0].length. But there is no rule that
says that all of the rows of A must have the same length (although an array created with
new BaseType[rows][columns] will always have that form). Each row in a 2D array is a
separate one-dimensional array, and each of those arrays can have a different length. In fact, it's
even possible for a row to be null. For example, the statement

A = new int[3][];

with no number in the second set of brackets, creates an array of 3 elements where all the
elements are null. There are places for three rows, but no actual rows have been created. You
can then create the rows A[0], A[1], and A[2] individually.
As an example, consider a symmetric matrix. A symmetric matrix, M, is a two-dimensional array
in which the number of rows is equal to the number of columns and satisfying M[i][j] equals
M[j][i] for all i and j. Because of this equality, we only really need to store M[i][j] for
i >= j. We can store the data in a "triangular matrix":

It's easy enough to make a triangular array, if we create each row separately. To create a 7-by-7
triangular array of double, we can use the code segment

double[][] matrix = new double[7][]; // rows have not yet been created!
for (int i = 0; i < 7; i++) {
matrix[i] = new double[i+1]; // Create row i with i + 1 elements.
}

We just have to remember that if we want to know the value of the matrix at (i,j), and if
i < j, then we actually have to get the value of matrix[j][i] in the triangular matrix. And
similarly for setting values. It's easy to write a class to represent symmetric matrices:

/**
* Represents symmetric n-by-n matrices of real numbers.
*/
public class SymmetricMatrix {

private double[][] matrix; // A triangular matrix to hold the data.

/**
* Creates an n-by-n symmetric matrix in which all entries are 0.
*/
public SymmetricMatrix(int n) {
matrix = new double[n][];
for (int i = 0; i < n; i++)
matrix[i] = new double[i+1];
}
/**
* Returns the matrix entry at position (row,col). (If row < col,
* the value is actually stored at position (col,row).)
*/
public double get( int row, int col ) {
if (row >= col)
return matrix[row][col];
else
return matrix[col][row];
}
/**
* Sets the value of the matrix entry at (row,col). (If row < col,
* the value is actually stored at position (col,row).)
*/
public void set( int row, int col, double value ) {
if (row >= col)
matrix[row][col] = value;
else
matrix[col][row] = value;
}

/**
* Returns the number of rows and columns in the matrix.
*/
public int size() {
return matrix.length; // The size is the number of rows.
}

} // end class SymmetricMatrix

This class is in the file SymmetricMatrix.java, and a small program to test it can be found in
TestSymmetricMatrix.java.

By the way, the standard function Arrays.copyOf() can't make a full copy of a 2D array in
a single step. To do that, you need to copy each row separately. To make a copy of a two-
dimensional array of int, for example:

int[][] B = new int[A.length][]; // B has as many rows as A.


for (int i = 0; i < A.length; i++) {
B[i] = Arrays.copyOf(A[i], A[i].length)); // Copy row i.
}

C++ Multidimensional Arrays


In this article, you'll learn about multi-dimensional arrays in C++. More specifically, how to
declare them, access them and use them efficiently in your program.
In C++, you can create an array of an array known as multi-dimensional array. For example:

int x[3][4];

Here, x is a two dimensional array. It can hold a maximum of 12 elements.

You can think this array as table with 3 rows and each row has 4 columns as shown below.
Three dimensional array also works in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements. You can think this example as: Each of the 2
elements can hold 4 elements, which makes 8 elements and each of those 8 elements can hold 3
elements. Hence, total number of elements this array can hold is 24.

Multidimensional Array Initialisation


You can initialise a multidimensional array in more than one way.

Initialisation of two dimensional array

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

Better way to initialise this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};

Initialisation 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};

Better way to initialise this array with same elements as above.

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}, {3, 1, 4, 9} }

};

Example 1: Two Dimensional Array


C++ Program to display all elements of an initialised two dimensional array.
1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int test[3][2] =
7. {
8. {2, -5},
9. {4, 0},
10. {9, 1}
11. };
12.
13. // Accessing two dimensional array using
14. // nested for loops
15. for(int i = 0; i < 3; ++i)
16. {
17. for(int j = 0; j < 2; ++j)
18. {
19. cout<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;
20. }
21. }
22.
23. return 0;
24. }

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

Example 2: Two Dimensional Array

C++ Program to store temperature of two different cities for a week and
display it.

1. #include <iostream>
2. using namespace std;
3.
4. const int CITY = 2;
5. const int WEEK = 7;
6.
7. int main()
8. {
9. int temperature[CITY][WEEK];
10.
11. cout << "Enter all temperature for a week of first city and then second
city. \n";
12.
13. // Inserting the values into the temperature array
14. for (int i = 0; i < CITY; ++i)
15. {
16. for(int j = 0; j < WEEK; ++j)
17. {
18. cout << "City " << i + 1 << ", Day " << j + 1 << " : ";
19. cin >> temperature[i][j];
20. }
21. }
22.
23. cout << "\n\nDisplaying Values:\n";
24.
25. // Accessing the values from the temperature array
26. for (int i = 0; i < CITY; ++i)
27. {
28. for(int j = 0; j < WEEK; ++j)
29. {
30. cout << "City " << i + 1 << ", Day " << j + 1 << " = " <<
temperature[i][j] << endl;
31. }
32. }
33.
34. return 0;
35. }

Output

Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23

Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23

Example 3: Three Dimensional Array

C++ Program to Store value entered by user in three dimensional array and
display it.
1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. // This array can store upto 12 elements (2x3x2)
7. int test[2][3][2];
8.
9. cout << "Enter 12 values: \n";
10.
11. // Inserting the values into the test array
12. // using 3 nested for loops.
13. for(int i = 0; i < 2; ++i)
14. {
15. for (int j = 0; j < 3; ++j)
16. {
17. for(int k = 0; k < 2; ++k )
18. {
19. cin >> test[i][j][k];
20. }
21. }
22. }
23.
24. cout<<"\nDisplaying Value stored:"<<endl;
25.
26. // Displaying the values with proper index.
27. for(int i = 0; i < 2; ++i)
28. {
29. for (int j = 0; j < 3; ++j)
30. {
31. for(int k = 0; k < 2; ++k)
32. {
33. cout << "test[" << i << "][" << j << "][" << k << "] = " <<
test[i][j][k] << endl;
34. }
35. }
36. }
37.
38. return 0;
39. }

Output

Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Value stored:


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
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

As the number of dimension increases, the complexity also increases tremendously


although the concept is quite similar.

Overview:

Arrays

ARRAYS IN C++
An array is a collection of elements of the same type placed in contiguous memory locations that
can be individually referenced by using an index to a unique identifier.
Five values of type int can be declared as an array without having to declare five different
variables (each with its own identifier).
For example, a five element integer array foo may be logically represented as;

where each blank panel represents an element of the array. In this case, these are values of type
int. These elements are numbered from 0 to 4, with 0 being the first while 4 being the last; In
C++, the index of the first array element is always zero. As expected, an n array must be declared
prior its use. A typical declaration for an array in C++ is:

type name [elements];

where type is a valid type (such as int, float ...), name is a valid identifier and the elements
field (which is always enclosed in square brackets []), specifies the size of the array.
Thus, the foo array, with five elements of type int, can be declared as:
int foo [5];

NOTE
: The elements field within square brackets [], representing the number of elementsin the array, must be a
constant expression, since arrays are blocks of static memory whose size must be known at compile time.

INITIALIZING ARRAYS
By default, are left uninitialized. This means that none of its elements are set to anyparticular
value; their contents are undetermined at the point the array is declared.
The initializer can even have no values, just the braces:

int baz [5] = { };

This creates an array of five int values, each initialized with a value of zero:

But, the elements in an array can be explicitly initialized to specific values when it is declared,
by enclosing those initial values in braces {}. For example:

int foo [5] = { 16, 2, 77, 40, 12071 };

This statement declares an array that can be represented like this:

The number of values between braces {} shall not be greater than the number of elements in the
array. For example, in the example above, foo was declared having 5 elements (as specified by
the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for
each element. If declared with less, the remaining elements are set to their default values (which
for fundamental types, means they are filled with zeroes). For example:

int bar [5] = { 10, 20, 30 };

Will create an array like this:


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 automatically a size for the
array that matches the number of values included between the braces {}:

int foo [] = { 16, 2, 77, 40, 12071 };

After this declaration, array foo would be five int long, since we have provided five
initialization values.
Finally, the evolution of C++ has led to the adoption of universal initialization also for
arrays. Therefore, there is no longer need for the equal sign between the declaration and the
initializer. Both these statements are equivalent:

int foo[] = { 10, 20, 30 };

int foo[] { 10, 20, 30 };

Here, the number of the array n is calculated by the compiler by using the formula n= #of
initializers/sizeof(int).
Static arrays, and those declared directly in a namespace (outside any function), are always
initialized. If no explicit initializer is specified, all the elements are default-initialized (with
zeroes, for fundamental types).

ARRAY ACCESSING
The values of any of the elements in an array can be accessed just like the value of a regular
variable of the same type. The syntax is:
name[index]

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

For example, the following statement stores the value 75 in the third element of foo:

foo [2] = 75;

and, for example, the following copies the value of the fourth element of foo to a variable called
x:
x = foo[3];

Therefore, the expression foo[2] or foo[4] is always evaluated to an int. Notice that the third
element of foo is specified foo[2], the second

one is foo[1], since the first one is foo[0]. It’s last element is therefore foo[4]. If we
write foo[5], we would be accessing the sixth element of foo, and therefore actually
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 errors on
compilation, but can cause errors on runtime. The reason for this being allowed
because index checking slows down program execution. 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 when
they are accessed. Do not confuse these two possible uses of brackets [] with arrays.

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


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

The main difference is that the declaration is preceded by the type of the elements,
while the access is not.

Some other valid operations with arrays:

foo[0] = a;
foo[i] = 75;
b = foo [i+2];
foo[foo[i]] = foo[i] + 5;
For example:

// arrays example
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};


int i, result=0;

int main ()
{
for ( i=0 ; i<5 ; i++ )
{
result += foo[i];
}
cout << result;
return 0;
}

12206

Multidimensional arrays

Multidimensional arrays can be described as "arrays of arrays". For example, a bi-


dimensional array can be imagined as a two-dimensional table made of elements, all of
them hold same type of elements.

Table represents a bi-dimensional array of 3 per 5 elements of type int. The C++
syntax for this is

int Table [3][5];

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

Table[1][3]

(remember that array indices always begin with zero).

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

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


Declares an array with an element of type char for each second in a century. This
amounts to more than 3 billion char! So this declaration would consume more than 3
gigabytes of memory! And such a declaration is highly improbable and it underscores
inefficient use of memory space.

At the end, multidimensional arrays are just an abstraction for programmers, since the
same results can be achieved with a simple array, by multiplying its indices:

int Table [3][5]; // is equivalent to


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

With the only difference that with multidimensional arrays, the compiler automatically
remembers the depth of each imaginary dimension. The following two pieces of code
produce the exact same result, but one uses a bi-dimensional array while the other
uses a simple array:

Multidimensional array
const int WIDTH = 5;
const int HEIGHT = 3;

int Table [HEIGHT][WIDTH];


int n,m;

int main ()
{
for (n=0; n<HEIGHT; n++)
for (m=0; m<WIDTH; m++)
{
Table[n][m]=(n+1)*(m+1);
}
}
Pseudo-multidimensional array
const int WIDTH = 5;
const int HEIGHT = 3;

int Table [HEIGHT * WIDTH];


int n,m;

int main ()
{
for (n=0; n<HEIGHT; n++)
for (m=0; m<WIDTH; m++)
{
Table[n*WIDTH+m]=(n+1)*(m+1);
}
}
None of the two code snippets above produce any output on the screen, but both
assign values to the memory block called jimmy in the following way:

Note that the code uses named constants for the width and height, instead of using
directly their numerical values. This gives the code a better readability, and allows
changes in the code to be made easily in one place.

Using Loop to input an Two-Dimensional Array from user


int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
for (col = 0; col < 5; col++)
cin >> mat[row][col];

Arrays as Parameters

Two-dimensional arrays can be passed as parameters to a function, and they are


passed by reference. This means that the function can directly access and modified the
contents of the passed array. When declaring a two-dimensional array as a formal
parameter, we can omit the size of the first dimension, but not the second; that is, we
must specify the number of columns. For example:

void print(int A[][3],int N, int M)

In order to pass to this function an array declared as:

int arr[4][3];

we need to write a call like this:

print(arr);

Here is a complete example:


#include <iostream>
using namespace std;
void print(int A[][3],int N, int M)
{
for (R = 0; R < N; R++)
for (C = 0; C < M; C++)
cout << A[R][C];
}
int main ()
{
int arr[4][3] ={{12, 29, 11},
{25, 25, 13},
{24, 64, 67},
{11, 18, 14}};
print(arr,4,3);
return 0;
}

Engineers use two dimensional arrays in order to represent matrices. The code for a
function that finds the sum of the two matrices A and B are shown below.

Function to find the sum of two Matrices


void Addition(int A[][20], int B[][20],int N, int M)
{
for (int R=0;R<N;R++)
for(int C=0;C<M;C++)
C[R][C]=A[R][C]+B[R][C];
}
Function to find out transpose of a matrix A

void Transpose(int A[][20], int B[][20],int N, int M)


{
for(int R=0;R<N;R++)
for(int C=0;C<M;C++)
B[R][C]=A[C][R];
}
Arrays as parameters

At some point, we may need to pass an array to a function as a parameter. In C++, it


is not possible to pass the entire block of memory represented by an array to a function
directly as an argument. But what can be passed instead is its address. In practice, this
has almost the same effect, and it is a much faster and more efficient operation.

To accept an array as parameter for a function, the parameters can be declared as the
array type, but with empty brackets, omitting the actual size of the array. For example:

void procedure (int arg[])


This function 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:

Code
// arrays as parameters
#include <iostream>
using namespace std;

void printarray (int arg[], int length) {


for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}

int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}
Solution
5 10 15
2 4 6 8 10

In the code above, 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.

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.

In a way, passing an array as argument always loses a dimension. The reason behind is
that, for historical reasons, arrays cannot be directly copied, and thus what is really
passed is a pointer. This is a common source of errors for novice programmers.
Although a clear understanding of pointers, explained in a coming chapter, helps a lot.

Anda mungkin juga menyukai