Laboratory Work 5

Use of Arrays

1 Laboratory Work Tasks

1.1 Sum of the Minimum and Maximum Elements

Write a program that calculates the sum of the minimum and maximum elements of an array of double precision floating point values. Implement separate functions to find the minimum and maximum elements.

1.2 Multiplication of Matrices

Write a program for filling two two-dimensional arrays (matrices) of the required sizes with pseudorandom numbers, finding the product of matrices and displaying the result on the screen.

1.3 Individual Assignment

You should create a program that defines and initializes a two-dimensional array of integer elements and then implements following activities:

  • transformation of the source array according to step one of the individual assignment
  • creation and filling of a new (one-dimensional) array of double precision floating point type elements according to step two of the individual assignment
  • output of both array elements

The program should display error messages if transformation or filling are not possible.

Variant number (student's number on the class list) Rule for transforming the first array (step one) Rule for filling the second array (step two).
Resulting array should contain:
Row count
m
Column count
n
1, 15
All elements with odd values should be doubled Square roots of minimal positive elements of rows
4
3
2, 16
All elements with even values should be replaced with their squares Cubic roots of minimal elements of columns
3
5
3, 17
All elements whose value is zero should be replaced with ones Natural logarithms of maximum positive elements of rows
3
4
4, 18
All elements with even values should be doubled Natural logarithms of minimal positive elements of columns
4
5
5, 19
All elements should be replaced with their absolute absolute values Minimal elements of columns
5
4
6, 20
All elements with even values should be tripled Cubic roots of diagonal elements
3
3
7, 21
All positive elements should be replaced with integer parts of their Briggs (base ten) logarithms Sums of negative elements of columns
4
5
8, 22
All negative elements should be replaced with their squares Square roots of diagonal elements
4
4
9, 23
All positive elements should be replaced with integer parts of their Napierian (natural) logarithms Products of negative elements of rows
5
4
10, 24
All positive elements should be replaced with integer parts of their square roots Maximum positive elements of rows
3
5
11, 25
All positive even elements should be doubled Cubic roots of maximum elements of columns
5
4
12, 26
All negative odd elements should be tripled Square roots of minimal positive elements of columns
3
4
13, 27
All negative odd elements should be doubled Sums of Briggs (base ten) logarithms of positive elements of rows
4
3
14, 28
All positive even elements should be tripled the maximum positive elements in each column divided by its Briggs (base ten) logarithms
3
5

To calculate standard mathematical functions you should include cmath header file.

1.4 Sorting an Array using Selection Sort Method (Additional Task)

Write a program that implements the sorting elements of an array of integers using Selection Sort method.

2 Guidelines

2.1 Definition of One-Dimensional Arrays

2.1.1 Concept of Arrays

A significant part of programming involves working with collections. A collection is a data structure that groups elements (items), which may have the same or different types, which can be accessed as a whole, and also allows work with individual elements. In most cases, collection contains objects of the same type. There are different methods of storing and accessing elements.

An array in the general sense is a data structure that provides access to an element through a specific key. For example, in so-called associative arrays, the key can be any object, for example, a number, letter, string, structure, etc.

In the simplest case, an array that supports only numeric indices: integers in a certain range. Array elements are stored contiguously in memory. Next we will work with the simplest (built-in) form by the array.

An array is actually the simplest collection. An array is a data structure that meets the following characteristics:

  • the array contains elements of the same type;
  • all elements of the array occupy a contiguous block of memory;
  • access to the elements is carried out by determining the index (number) of the element in the array.

Arrays can be one-dimensional and multidimensional. In programming, one-dimensional arrays are used to store a large number of identical variables. Elements can be individual numbers (measurements of temperature, voltage, number of days in months, number of lessons on different days of the week, number of passengers in railway cars, etc.), strings (surnames, names of cities, countries, etc.) or complex objects.

Two-dimensional arrays are used, for example, to work with matrices or other rectangular tables. It is much less common to create arrays with more dimensions.

Work with arrays is implemented in almost all programming languages. There are syntactic differences in the mechanisms for addressing elements. Usually, elements are referred to by specifying the index in parentheses or square brackets. In C++, the index is specified in square brackets.

Array elements in most languages are numbered starting from zero. This makes it easier to access elements. Elements are located sequentially in memory

a[0]
a[1]
...
a[n - 1]

If addr_0 is the address of the element at index 0 (the first element) of the array, and sizeof(element) is the number of bytes for storing one element of the array, the address of the element with index i (addr_i) can be easily calculated by the formula

addr_i = addr_0 + i * sizeof(element)

As can be seen from this formula, elements can be accessed almost as quickly as individual variables. In no case, to select an element by index, it is not necessary to sequentially traversal through the elements.

2.1.2 Creation of One-Dimensional Arrays

The following syntax is used to create a one-dimensional array in C++:

element_type array_name[number_of_elements];

The array name is an identifier constructed according to general rules. If it is difficult to determine the physical meaning of the array, you can use a, b, c, or arr. The number of elements is determined by a constant. The number of array elements is called its size, as well as its length.

For example, you can create an array of ten elements of the type double:

double a[10];

In our example, the compiler allocates a block of memory in which 10 numbers of double type can be placed. Since each such number occupies 8 bytes, the compiler reserves 80 consecutive bytes of memory.

In the C++ code, to obtain a separate element of the array, the subscript operation ([]) is used. In our example, a[0] refers to the initial element. The last index should be one less than the number of elements. In our case, the last element can be obtained as follows: a[9].

You can use constants (constant expressions) to determine the size of the array. You cannot use constants that cannot be computed at compile time, as well as variables:

const int n = 10;      // explicit constant
int firstArr[n];       // OK
const int n1 = n + 3;  // constant expression
int secondArr[n1 + 2]; // OK: the size can be calculated by the compiler
// The following constant cannot be calculated by the compiler:
const int m = std::rand();
int thirdArr[m];       // compile error
int m1 = 4;            // variable
int fourthArr[m1];     // compile error

C++ has no mechanism for resizing a built-in array that has already been created. The only way is to create a new array of another length and copy the existing elements there.

2.1.3 Initialization of Arrays

You can initialize a simple array, when you first define this array. After the array name, you can put an equal sign (=) and a list of comma-separated values enclosed in braces. For example,

int integerArray[5] = { 1, 2, 3, 4, 5 };

defines integerArray to be an array of five integers. It assigns integerArray[0] the value 1, integerArray[1] the value 2, and so forth.

If you omit the size of the array, an array just big enough to hold the initialization is created. This definition is the same as previous one:

int integerArray[] = { 1, 2, 3, 4, 5 };

You cannot initialize more elements than you've declared for the array. Therefore,

int integerArray[5] = { 1, 2, 3, 4, 5, 6 };

generates a compiler error. It is legal, however, to write

int integerArray[5] = { 1, 2 };

Any remaining elements are value-initialized to zero.

2.2 Using Arrays

2.2.1 Working with Array Elements

Individual elements of arrays are accessed using the array subscript operator ([]). The value of the index is set using a constant, variable or expression, if it can be converted to an integer type:

int i = 0;
integerArray[i] = 11;
int k = integerArray[2];
integerArray[k % 10 + 1] = 0;

A for loop is usually used to perform typical operations on array elements. If n is the number of the array elements, then in order to go through all the elements, we create the following loop:

const int n = 5;
int a[n];
for (int i = 0; i < n; i++)
    // work with individual elements

For example, in this way, you can write the value 0 in all elements of an array of integers:

const int n = 5;
int a[n];
for (int i = 0; i < n; i++) {
    a[i] = 0;
}

A typical mistake of beginners is to organize the loop including n:

const int n = 5;
int a[n];
for (int i = 0; i <= n; i++) { // i cannot be equal to n
    a[i] = 0; // error at the last step of the loop
}

The reaction may be different depending on the compiler and its version . For example, there may be an error message when running a program, but sometimes the values of other variables are eventually changed.

It is also possible to read arrays from the keyboard and display the array on the screen only in a loop. This is how you can read elements from the keyboard:

const int n = 6;
double a[n];
for (int i = 0; i < n; i++) {
    cin >> a[i];
}

This is how all elements can be displayed on the screen:

for (int i = 0; i < n; i++) {
    cout << a[i] << " ";
}
cout << endl;

In the above example, the elements to be output are separated by spaces. You can also use tab or new line characters if needed.

You cannot assign one array to another. This expression generates compile-time error.

const int n = 4;
double a[n];
double b[n] = { 11, 72, 4, 18 };
a = b; // compile-time error

You should create a special loop to copy one array into another:

const int n = 4;
double a[n]; 
double b[n] = { 11, 72, 4, 18 };
for (int i = 0; i < n; i++) {
    a[i] = b[i];
}

Within the block in which the array is defined, its length can be obtained using the expression sizeof(array_name)/sizeof(element_type). Example:

const int n = 6;
double a[n];
for (int i = 0; i < sizeof(a)/sizeof(double); i++) {
    cin >> a[i];
}

2.2.2 Using Range-Based Loops

You cannot create an array of references, but you can define a reference to any particular element of an array:

double a[] = { 1, 2, 4, 8 };
double& y = a[3];
y = 16; // a[3] = 16

You can also create a reference to the entire array and use it as an array:

double (&b)[4] = a;
b[0] = 3;

To iterate array elements without using index, a new version of C++ language (starting from C++11) offers an alternative cycle construction: range-based for loop:

for (element_type &variable: array)
    looping_body

Within a loop body, you can use a variable as the current element of an array. For example, this way you can assign ones to all the elements of an array:

int arr[4];
for (int& k : arr) {
    k = 1;
}

If no modification of elements is provided in the body of the loop, it is better to describe a reference to a constant object:

for (const int &k : arr) {
    std::cout << k << " ";
}

You cannot use an index or bypass part of an array in the body of the loop.

Unfortunately, a range-based for statement can only be used for arrays within the blocks in which those arrays are defined, or if the array is passed to the function by reference.

2.2.3 Examples of Tasks Related to Arrays

Typical actions with arrays of numbers are, for example, finding sums, products, elements with the largest, smallest value, etc. In the following example, we calculate the product of the array elements:

#include <iostream>
using namespace std;

int main() {
    double a[] = { 1, 2, 3, 4 };
    double product = 1;
    for (const double& elem : a) {
        product *= elem;
    }
    cout << product; // 24
    return 0;
}

If the actions do not involve all elements, a range-based loop should not be used. This is how you can find the sum of array elements with even indices:

#include <iostream>
using namespace std;

int main() {
    const int n = 6;
    double a[n] = { 1, 2, 3, 2, 1, 6 };
    double sum = 0;
    for (int i = 0; i < n; i += 2) {
        sum += a[i];
    }
    cout << sum; // 5
    return 0;
}

In the example 3.2, the index of the maximum element of the array is searched.

A separate group of actions is changing the arrangement of elements, in particular, sorting by some criterion. In the example below, neighboring elements are swapped:

#include <iostream>
using namespace std;

void swap(int& x, int& y) {
    int z = x;
    x = y;
    y = z;
}

int main() {
    const int n = 5;
    int a[n] = { 1, 2, 3, 2, 10 };
    for (int i = 0; i < n - 1; i += 2) {
        swap(a[i], a[i + 1]);
    }
    for (const int& item : a) {
        cout << item << " "; // 2 1 2 3 10
    }
    return 0;
}

The last element remains in its place, because it has no partner.

The program that implements sorting by the bubble method is shown in the example 3.3.

2.3 One-Dimensional Arrays as Function Parameters

Array names can be used as actual arguments of a function. An array name without square brackets is implicitly converted to the address of the first element of the array. A copy of this address is assigned to the corresponding parameter. The function can use this address to access the array elements. For example, the function calculates and returns the sum of the elements of an array of length n:

#include <iostream>
using namespace std;

const int n = 5;

double sum(double arr[]) {
    double result = 0;
    for (int i = 0; i < n; i++) {
        result += arr[i];
    }
    return result;
}

int main() {
    double a[] = { 1, 2, 4, 8, 16 };
    double y = sum(a);
    cout << y << endl; // 31
    return 0;
}

Note: it is not possible to use a loop built on a range in the body of a sum() function, because the array is created in another function, and we are actually working with the address of the first element.

There is no way to get the actual number of array elements inside the function. Therefore, if we want the size of the array, we pass it as a separate parameter:

#include <iostream>
using namespace std;

double sum(double arr[], int n) {
    double result = 0;
    for (int i = 0; i < n; i++) {
        result += arr[i];
    }
    return result;
}

int main() {
    double a[] = { 1, 2, 4, 8, 16 };
    double y = sum(a, 5);
    cout << y << endl; // 31
    y = sum(a, 4);
    cout << y << endl; // 15
    return 0;
}

As you can see from the code, it is possible to calculate the sum of some part of elements. It is also possible to calculate the sum of different arrays with different lengths, the main thing is that the type of elements is double (in this example).

Since in the function we receive the address of the array, we work with the same array. Therefore, changes made to the elements remain in the calling function. For example,

#include <iostream>

using namespace std;

void spoil(double arr[]) {
    arr[0] = 0;
}

int main() {
    const int n = 4;
    double a[] = {1, 2, 4, 8};
    for (int i = 0; i < n; i++) {
        cout << a[i] << ' '; //1 2 4 8
    }
    cout << endl;
    spoil(a);
    for (int i = 0; i < n; i++) {
        cout << a[i] << ' '; //0 2 4 8
    }
    cout << endl;
    return 0;
}

In order to avoid accidentally changing the values of the array elements in the function, the parameter can be passed with the const modifier:

void f(const double arr[]) {
    // ... the compiler will not allow changing the values of elements
}

Array type parameters can also be passed by reference. In this case, the array in the function can be processed as an array at the point of call. The reference name together with the ampersand must be enclosed in parentheses, otherwise the compiler will interpret it as an array of references, which is not allowed by the syntax. The previously created function for finding the sum of the array elements can be implemented as follows:

#include <iostream>
using namespace std;

const int n = 5;

double sum(double (&arr)[n]){ // brackets around &arr are required
    double result = 0;
    for (const double &x : arr) {
        result += x;
    }
    return result;
}

int main() {
    double a[] = { 1, 2, 4, 8, 16 };
    double y = sum(a);
    cout << y << endl; // 31
    return 0;
}

As can be seen from the implementation, unlike the previously defined functions, a loop built on a range can be used in the function body.

You can also not pass the array length, because it is determined before the call. It should be remembered that such a function only works with an array of a previously determined length.

2.4 Filling Arrays with Pseudo-Random Numbers

When debugging and testing programs involving arrays, we can fill arrays with random or pseudo-random numbers is often used. Random and pseudo-random numbers were discussed earlier. Pseudorandom numbers that repeat every time can be used to debug the program.

The following program fills an array of five integers with pseudo-random numbers from 0 to 19, inclusive:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    const int n = 5;
    int randomArr[n];
    for (int& item : randomArr) {
        item = rand() % 20;
    }
    for (const int& item : randomArr) {
        cout << item << " "; // 1 7 14 0 9
    }
    return 0;
}

After each start results will be the same.

To obtain different sequences, we initialize the pseudorandom number generator with the current time using the time(0) function (ctime header file). Now the program will look like this:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    const int n = 5;
    int randomArr[n];
    srand(time(0));
    for (int& item : randomArr) {
        item = rand() % 20;
    }
    for (const int& item : randomArr) {
        cout << item << " "; // random numbers from 0 to 19 inclusive
    }
    return 0;
}

Random numbers should be used for testing rather than for debug.

2.5 Multidimensional Arrays

It is possible to create arrays of more than one dimension. Each dimension is represented as a subscript in the array. Therefore, a two-dimensional array has two subscripts; a three-dimensional array has three subscripts; and so on. Arrays can have any number of dimensions, however most of the arrays you create will be of one or two dimensions.

If the program contains such a definition,

// Previously, integer constants m and n were defined
double a[m][n];

the compiler will create an array of floating point numbers from m rows and n columns, which represents a rectangular table (matrix):

a[0][0]
a[0][1]
...
a[0][n - 1]
a[1][0]
a[1][1]
...
a[1][n - 1]
...
...
...
...
a[m - 1][0]
a[m - 1][1]
...
a[m - 1][n - 1]

Physically, such an array will be located in m × n sequentially arranged memory cells:

a[0][0]
a[0][1]
...
a[0][n - 1]
a[1][0]
a[1][1]
...
a[1][n - 1]
...
a[m - 1][0]
a[m - 1][1]
...
a[m - 1][n - 1]

In fact, in memory we work with a one-dimensional array. Such an array can be created explicitly:

double b[m * n];
b[i * n + j] = 0; // for a two-dimensional array a[i][j] = 0;

Using a two-dimensional array is more comfortable for the programmer.

You can initialize multidimensional arrays. You assign the list of values to array elements in order, with the last array subscript changing while each of the former holds steady. Therefore, if you have an array

int theArray[5][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

the first three elements go into theArray[0]; the next three into theArray[1]; and so forth.

For the sake of clarity, you could group the initializations with braces. For example,

int theArray[5][3] = { { 1,  2,  3 },
                       { 4,  5,  6 },
                       { 7,  8,  9 },
                       {10, 11, 12 },
                       {13, 14, 15 } };

The compiler uses inner curly braces to clearly define the boundaries of each individual row of the array. Using them makes the expression easier to read. If fewer elements are specified within the inner braces than the size of the row, the remaining elements in that specific row are automatically filled with zeros (the default values ​​for the given type). If, by mistake, more elements are specified within the inner braces than the row size allows, the compiler will issue an error.

Values ​​must be separated by commas. The entire initialization set must be enclosed in curly braces and must end with a semicolon.

Only the first pair of square brackets may be omitted:

int theArray[][3] = { { 1,  2,  3 },
                      { 4,  5,  6 },
                      { 7,  8,  9 },
                      {10, 11, 12 },
                      {13, 14, 15 } };

In this case, compiler counts first size automatically.

As with one-dimensional arrays, elements whose values are missing from the list are filled with zeros (default values for a certain type). For example, the values of all array elements will be set to zeros:

const int m = 4;
const int n = 3;
int arr[m][n] = { };

Nested loops are usually used to work with elements of a multidimensional array. For example, this is how we can write into elements the sum of their indices:

for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        arr[i][j] = i + j;
    }
}

Using i index for the row number and j index for the column number is optional, but is traditional for working with two-dimensional arrays.

You can apply range-based loops to multidimensional arrays. For example, this is how we can put ones into all array elements:

for (auto& row : arr) {
    for (int& item : row) {
        item = 1;
    }
    cout << endl;
}

This is how we can display the elements of a two-dimensional array line by line:

for (const auto &row : arr) {
    for (const int &item : row) {
        cout << item << "\t";
    }
    cout << endl;
}

The use auto here has reason, as otherwise the loop header would be more complex:

for (const int(&row)[n] : arr)

There is a problem with a transferring of multidimensional arrays to the functions. In fact, it is necessary to create separate functions, clearly indicating the second, third and other dimensions (except for the first). For example:

double f(double a[][3]) {
    return a[1][1];
}

This function can be invoked:

int main() {
    double arr[][3] = { { 1, 2, 3 },
                        { 4, 5, 6 } };
    cout << f(arr);
    return 0;
}

This approach is not commonly used; pointers are often used instead.

Multidimensional arrays can also be passed by reference. For example, the function for calculating the sum of all elements of a two-dimensional array can be implemented as follows:

#include <iostream>
using namespace std;

const int m = 2;
const int n = 3;

int sum(int (&arr)[m][n]) {
    int result = 0;
    for (const auto& row : arr) {
        for (const int& item : row) {
            result += item;
        }
    }
    return result;
}

int main() {
    int a[m][n] = { { 1, 2, 4 },
                    { 8, 16, 32 } };
    double y = sum(a);
    cout << y << endl; // 63
    return 0;
}

As with one-dimensional arrays, this function only works with arrays of a specified size.

3 Sample Programs

3.1 Sum of Elements

Suppose you need to find the sum of elements of a one-dimensional array of integers. The program can be as follows:

#include <iostream>
using namespace std;

int main() {
    double a[] = { 1, 2, 3, 4 };
    double s = 0;
    for (int i = 0; i < sizeof(a)/sizeof(double); i++) {
        s += a[i];
    }
    cout << s << endl; // 10;
    return 0;
}

3.2 Maximal Element

The following program finds the maximum element of an integer array. It is often useful to find its index rather than only its value, since the value can then be accessed through that index.

#include <iostream>

using namespace std;

int main() {
    const int n = 4;
    int a[] = { 1, 2, 4, 3 };
    int indexOfMax = 0;
    for (int i = 1; i < n; i++) {
        if (a[i] > a[indexOfMax]) {
            indexOfMax = i;
        }
    }
    cout << indexOfMax << ' ' << a[indexOfMax];
    return 0;
}

3.3 Sorting

It is necessary to write a program that sorts elements of double array in ascending order using bubble sort algorithm.

#include<iostream>
using namespace std;

void sort(double a[], int size) {
    bool mustSort; // We must repeat sorting
                   // if mustSort is equal true
    do {
        mustSort = false;
        for (int i = 0; i < size - 1; i++) {
            if (a[i] > a[i + 1]) {
                double temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                mustSort = true;
            }
        }
    } while (mustSort);
}

int main() {
    const int n = 5;
    double a[] = { 11, 2.5, 4, 3, 5 };
    sort(a, n);
    for (double &item : a) {
        cout << item << ' ';
    }
    return 0;
}

3.4 Finding the Sum of Matrices

Two-dimensional arrays are often used to perform operations on mathematical matrices. The following program demonstrates finding the sum of matrices. The source matrices are filled with pseudorandom numbers.

#include <cstdio>
#include <iostream>
using namespace std;

// The function returns a valid value between 0 and 100
double nextRandom() {
    return (rand() % 10000) / 100.;
}

int main() {
    const int m = 3;
    const int n = 4;
// Create and fill array a:
    double a[m][n] = { };
    for (auto& row : a) {
        for (double& item : row) {
            item = nextRandom();
        }
    }
    for (const auto& row : a) {
        for (const double& item : row) {
            cout << item << "\t";
        }
        cout << endl;
    }
    cout << endl;
// Create and fill array b:
    double b[m][n] = { };
    for (auto& row : b) {
        for (double& item : row) {
            item = nextRandom();
        }
    }
    for (const auto& row : b) {
        for (const double& item : row) {
            cout << item << "\t";
        }
        cout << endl;
    }
    cout << endl;
// Calculate and output the sum of matrices:
    double c[m][n] = { };
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    for (const auto& row : c) {
        for (const double& item : row) {
            cout << item << "\t";
        }
        cout << endl;
    }
    return 0;
}

As you can see from the code, a range-based loop can be used only if we do not use index values.

This program can be split into parts and the code can be moved to different functions. We will pass the arrays by reference:

#include <cstdio>
#include <iostream>
using namespace std;

// The function returns a valid value between 0 and 100
double nextRandom() {
    return (rand() % 10000) / 100.;
}

const int m = 3;
const int n = 4;

void fillMatrix(double(&arr)[m][n]) {
    for (auto& row : arr) {
        for (double& item : row) {
            item = nextRandom();
        }
    }
}

void printMatrix(double (&arr)[m][n]) {
    for (const auto& row : arr) {
        for (const double& item : row) {
            cout << item << "\t";
        }
        cout << endl;
    }
    cout << endl;
}

void sumOfMatrices(double(&a)[m][n], double(&b)[m][n], double (&c)[m][n]) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
}

int main() {
    // Create and fill array a:
    double a[m][n] = { };
    fillMatrix(a);
    printMatrix(a);
    // Create and fill array b:
    double b[m][n] = { };
    fillMatrix(b);
    printMatrix(b);
    // Calculate and output the sum of matrices:
    double c[m][n] = { };
    sumOfMatrices(a, b, c);
    printMatrix(c);
    return 0;
}

As already mentioned, functions only work with arrays of specified sizes.

3.5 Sum of Products

The following program defines a two-dimensional array and calculates the sum of the products of its rows.

#include<iostream>
using namespace std;

int main() {
    const int  m = 4;
    const int  n = 3;
    int a[m][n] = { { 1, 2, 3 },
                    { 2, 3, 4 },
                    { 0, 1, 2 },
                    { 1, 1, 12} };
    int sum = 0;
    for (const auto &row : a) {
        int product = 1;
        for (const int &item : row) {
            product *= item;
        }
        sum += product;
    }
    cout << sum;
    return 0;
}

3.6 Replacement

It is necessary to write a program that replaces all negative elements of a two-dimensional array with zeros.

#include<iostream>
using namespace std;

int main() {
    const int m = 3;
    const int n = 3;
    double a[][n] = { { 1,  -2,  3 },
                      { 2.1, 3, -4 },
                      { 0,-0.5, 11 } };
    for (auto& row : a) {
        for (double& item : row) {
            if (item < 0) {
                item = 0;
            }
        }
    }
    for (const auto& row : a) {
        for (const double& item : row) {
            cout << '\t' << item;
        }
        cout << endl;
    }
    return 0;
}

4 Exercises

  1. Write a program that reads unsigned short integers and prints their binary representation in reverse order.
  2. Write a program that calculates sum of positive elements of an array of doubles.
  3. Write a program that defines an array of doubles and calculates sum of elements with odd indices.
  4. Write a program that defines an array of integers and calculates sum of even elements.
  5. Write a program that defines two-dimensional array and calculates the product of the maximal elements of its columns.

5 Review Questions

  1. What is an array? Where are arrays used?
  2. What ensures the efficiency of access to array elements?
  3. What is subscript operator?
  4. What is starting index of an array?
  5. Can you use variables to determine the length of an array?
  6. Can you change the size of an array after creation?
  7. How to add a new element to the end of the array?
  8. How to enter array elements from the keyboard?
  9. How to display the elements of the array in the console window?
  10. How to copy values of elements from one array to another?
  11. How to get the array length at runtime?
  12. How to create an array of references and reference to array?
  13. What is range-based loop?
  14. What are the restrictions on using range-based loops?
  15. How to transfer arrays to functions?
  16. How to get the length of an array inside the function where this array is passed?
  17. How to fill an array with random numbers?
  18. What are multidimensional arrays used for?
  19. How to determine the number of columns in a two-dimensional array?
  20. How to initialize two-dimensional array?
  21. How to apply range-based loop for 2D arrays?
  22. How to pass a multidimensional array to a function?

 

up