0% found this document useful (0 votes)
111 views

Lecture 9-C++ Arrays

The document discusses C++ arrays. It defines an array as an ordered collection of elements of the same type. Arrays allow storing multiple variables of the same type in contiguous memory locations. The key points made are: - Arrays have a predefined size that must be specified during declaration. - Array elements are accessed using an index with values starting from 0. - Arrays can be initialized during declaration by providing initial values. Empty elements are initialized to 0 by default. - The sizeof() operator returns the total memory size of an array. The length is obtained by dividing the size by the element type size. - Loops like for can be used to iterate through and access all elements of an array.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

Lecture 9-C++ Arrays

The document discusses C++ arrays. It defines an array as an ordered collection of elements of the same type. Arrays allow storing multiple variables of the same type in contiguous memory locations. The key points made are: - Arrays have a predefined size that must be specified during declaration. - Array elements are accessed using an index with values starting from 0. - Arrays can be initialized during declaration by providing initial values. Empty elements are initialized to 0 by default. - The sizeof() operator returns the total memory size of an array. The length is obtained by dividing the size by the element type size. - Loops like for can be used to iterate through and access all elements of an array.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Lecture 9: C++ Array

So far in constructing our building we have named each brick (variable). That is fine for a small
number of bricks, but what happens when we want to construct something larger? We would like
to point to a stack of bricks and say, "That's for the left wall. That's brick 1, brick 2, brick 3. . . ."
In C++, Array is an ordered collection of elements of same type.
For example, the following is an array of integers.
• {7, 3, 8, 7, 2}
And the following is an array of strings.
• {"apple", "banana", "cherry"}
Arrays allow us to do something similar with variables. An array is a set of consecutive memory
locations used to store data. Each item in the array is called an element. The number of elements
in an array is called the dimension/length of the array. A typical array declaration is:
// List of data to be sorted and averaged
int data_list[3];
This declares data_list to be an array of the three elements data_list[0], data_list [1], and
data_list[2], which are separate variables. To reference an element of an array, you use a number
called the index (the number inside the square brackets [ ]).
Point to note about Arrays
• It is a group of variables of similar data types referred to by a single element.
• Its elements are stored in a contiguous memory location.
• The size of the array should be mentioned while declaring it.
• Array elements are always counted from zero (0) onward.
• Array elements can be accessed using the position of the element in the array.
• The array can have one or more dimensions.
Thus, An array in C++ or be it in any programming language is a collection of similar data items
stored at contiguous memory locations and elements can be accessed randomly using indices of
an array. They can be used to store the collection of primitive data types such as int, float,
double, char, etc of any particular type. To add to it, an array in C++ can store derived data types
such as structures, pointers etc. Given below is the picture representation of an array.

1|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ Array Declaration

dataType arrayName[arraySize];

For example,

int x[6];

Here,
• int - type of element to be stored
• x - name of the array
• 6 - size of the array

Access Elements in C++ Array

In C++, each element in an array is associated with a number. The number is known as an array
index. We can access elements of an array by using those indices.

// syntax to access array elements

array[index];

Consider the array x we have seen above.

Elements of an array in C++

Few Things to Remember:


• The array indices start with 0. Meaning x[0] is the first element stored at index 0.
• Array elements are accessed by using an integer index. Array index starts with 0 and goes
till the size of the array minus 1. If the size of an array is n, the last element is stored at
index (n-1). In this example, x[5] is the last element.
• The name of the array is also a pointer to the first element of the array.
• Elements of an array have consecutive addresses. For example, suppose the starting address
of x[0] is 2120.

2|Page
@myco…TCBE 2202 Computing for Civil Engineering
Then, the address of the next element x[1] will be 2124, the address of x[2] will be 2128, and
so on. Here, the size of each element is increased by 4. This is because the size of int is 4
bytes.

C++ Array Initialization


In C++, it's possible to initialize an array during declaration. For example,

// declare and initialize and array


int x[6] = {19, 10, 8, 17, 9, 15};

C++ Array elements and their data


Another method to initialize array during declaration:

// declare and initialize an array


int x[] = {19, 10, 8, 17, 9, 15};

Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.

C++ Array with Empty Members


In C++, if an array has a size n, we can store upto n number of elements in the array. However,
what will happen if we store less than n number of elements.

For example,

// store only 3 elements in the array

int x[6] = {19, 10, 8};

3|Page
@myco…TCBE 2202 Computing for Civil Engineering
Here, the array x has a size of 6. However, we have initialized it with only 3 elements. In such
cases, the compiler assigns random values to the remaining places. Oftentimes, this random value
is simply 0.

Empty array members are automatically assigned the value 0

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9


mark[3] = 9;

// take input from the user


// store the value at third position
cin >> mark[2];

// take input from the user


// insert at ith position
cin >> mark[i-1];

// print first element of the array


cout << mark[0];

// print ith element of the array


cout >> mark[i-1];

4|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ Array Size
Get the Size of an Array: To get the size of an array, you can use the sizeof() operator:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result: 20
Why did the result show 20 instead of 5, when the array contains 5 elements?
It is because the sizeof() operator returns the size of a type in bytes. You learned from the Data
Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5
elements) = 20 bytes.
To find out how many elements an array has, you have to divide the size of the array by the size
of the data type it contains:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
Result: 5

C++ Arrays and Loops


Loop through an Array: You can loop through the array elements with the for loop.
This example outputs the index of each element together with its value:
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
And this example shows how to loop through an array of integers:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}

5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: Displaying Array Elements
#include <iostream>
using namespace std;

int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements


// using range based for loop
for (const int &n : numbers) {
cout << n << " ";
}

cout << "\nThe numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}
Run Code

Output

The numbers are: 7 5 6 12 35

The numbers are: 7 5 6 12 35

Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have
printed numbers[i].
We again used a range-based for loop to print out the elements of the array. To learn more about
this loop, check C++ Ranged for Loop. https://www.programiz.com/cpp-programming/ranged-for-loop

6|Page
@myco…TCBE 2202 Computing for Civil Engineering
Note: In our range-based loop, we have used the code const int &n instead of int n as the range
declaration. However, the const int &n is more preferred because:

1. Using int n simply copies the array elements to the variable n during each iteration. This is
not memory-efficient.
&n, however, uses the memory address of the array elements to access their data without
copying them to a new variable. This is memory-efficient.
2. We are simply printing the array elements, not modifying them. Therefore, we use const so
as not to accidentally change the values of the array.

Example 2: Take Inputs from User and Store Them in an Array


#include <iostream>
using namespace std;

int main() {

int numbers[5];

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

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;

Run Code

7|Page
@myco…TCBE 2202 Computing for Civil Engineering
Output

Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15

Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an
input from the user and stored it in numbers[i].
Then, we used another for loop to print all the array elements.

Example 3: Display Sum and Average of Array Elements Using for Loop

#include <iostream>
using namespace std;

int main() {

// initialize an array without specifying size


double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;

cout << "The numbers are: ";

// print array elements


// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";

// calculate the sum


sum += n;

// count the no. of array elements


++count;
}

8|Page
@myco…TCBE 2202 Computing for Civil Engineering
// print the sum
cout << "\nTheir Sum = " << sum << endl;

// find the average


average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}
Run Code

Output

The numbers are: 7 5 6 12 35 27


Their Sum = 92
Their Average = 15.3333

In this program:
1. We have initialized a double array named numbers but without specifying its size. We also
declared three double variables sum, count, and average.
Here, sum =0 and count = 0.
2. Then we used a range-based for loop to print the array elements. In each iteration of the loop,
we add the current array element to sum.
3. We also increase the value of count by 1 in each iteration, so that we can get the size of the
array by the end of the for loop.
4. After printing all the elements, we print the sum and the average of all the numbers. The
average of the numbers is given by average = sum / count;
Note: We used a ranged for loop instead of a normal for loop. A normal for loop requires us to
specify the number of iterations, which is given by the size of the array. But a ranged for loop
does not require such specifications.

C++ Array Out of Bounds

If we declare an array of size 10, then the array will contain elements from index 0 to 9. However,
if we try to access the element at index 10 or more than 10, it will result in Undefined Behaviour.

9|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ Multidimensional Arrays
In this tutorial, we'll learn about multi-dimensional arrays in C++. More specifically, how to
declare them, access them, and use them efficiently in our program.

In C++, we can create an array of arrays, known as a multidimensional array. To declare a multi-
dimensional array, define the variable type, specify the name of the array followed by square
brackets which specify how many elements the main array has, followed by another set of square
brackets which indicates how many elements the sub-arrays have:

For example:

int x[3][4];

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


We can think of this array as a table with 3 rows and each row has 4 columns as shown below.

Elements in two-dimensional array in C++ Programming

Three-dimensional arrays also work in a similar way. For example:

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

This array x can hold a maximum of 24 elements.


We can find out the total number of elements in the array simply by multiplying its dimensions:

2 x 4 x 3 = 24

10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Multidimensional Array Initialization
Like a normal array, we can initialize a multidimensional array in more than one way.

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.

Initializing a two-dimensional array in C++

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.

11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
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}

... .. ...

... .. ...

Access the Elements of a Multi


Multi-
ulti-Dimensional Array
To access an element of a multi-dimensional array, specify an index number in each of the
array's dimensions.
This statement accesses the value of the element in the first row (0) and third column (2) of the
letters array.
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"

12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Change Elements in a Multi-Dimensional Array
To change the value of an element, refer to the index number of the element in each of the
dimensions:
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
cout << letters[0][0]; // Now outputs "Z" instead of "A"

Loop through a Multi-Dimensional Array

To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.
The following example outputs all elements in the letters array:
Example
#include <iostream>
using namespace std;

int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

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


for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}

13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
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
// 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;
}
Run Code
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

14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
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: Loop through a three-dimensional array

This example shows how to loop through a three-dimensional array:


Example
#include <iostream>
using namespace std;

int main() {
string letters[2][2][2] = {
{{ "A", "B" },{ "C", "D" }},
{{ "E", "F" },{ "G", "H" }}
};

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


for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << letters[i][j][k] << "\n";
}
}
}
return 0;
}

15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 3: 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) {
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;
}
Run Code

16 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
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 4: Three Dimensional Array


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

#include <iostream>
using namespace std;

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

17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
// 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;
}
Run Code

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

18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we
want to store a large number of instances, it becomes difficult to manage them with normal
variables. The idea of an array is to represent many instances in one variable.

Why Multi-Dimensional Arrays? Multi-dimensional arrays are great at representing grids.

Advantages of using arrays:


arrays:-
• Code Optimization: we can retrieve or sort the data efficiently.
• Random access of elements using the array index: We can get any data located at an index
position.
• Use of fewer lines of code as it creates a single array of multiple elements.
• Easy access to all the elements.
• Traversal through the array becomes easy using a single loop.
• Sorting becomes easy as it can be accomplished by writing fewer lines of code.

Disadvantages:-
Disadvantages:-
• Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size
at runtime. Thus, arrays allows a fixed number of elements to be entered which is decided at
the time of declaration. Unlike a linked list, an array in C++ is not dynamic.
• Insertion and deletion of elements can be costly since the elements are needed to be managed
in accordance with the new memory allocation.

19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering

You might also like