Last Updated:

C++ Arrays | Examples

C++ Arrays

An array is a collection of data that has the following properties:

  • All elements of the array are of the same type;
  • The array has the same name for all elements.
  • access to a specific element of the array is carried out by index(s).

1. Declare an array

 

The array declaration has the following syntax:


<type specification> <name> [<constant expression>]; <type specification> <name> [ ];

Here, square brackets are an element of syntax, not a sign of an optional design.

An array declaration can have one of the two syntactic forms listed above. The square brackets following the name are an indication that the variable is an array. A constant expression enclosed in square brackets determines the number of elements in the array. Indexing array elements in C++ starts from scratch. Thus, the last element of the array has an index one less than the number of elements in the array.

In the second syntactic form, the constant expression in square brackets is omitted. This form can be used if an initializer is present in the array declaration, or the array is declared as a formal function parameter, or the declaration is a reference to the array declaration elsewhere in the program. However, for a multidimensional array, only the first dimension can be omitted.

A multidimensional array, or array of arrays, is declared by specifying a sequence of constant expressions in square brackets following the name:
<type specification> <name> [<constant expression>][<constant expression>] ... ;

Each constant expression determines the number of elements in a given array dimension, so declaring a two-dimensional array contains two constant expressions, a three-dimensional one contains three, and so on.

An array can consist of elements of any type other than the void type and functions, i.e. the elements of an array can have a basic, enumerable, structural type, be a union, a pointer or an array.

Examples of array declarations

int x[10];A one-dimensional array of 10 integers. The indices change from 0 to 9.
double y[2][10];A two-dimensional array of real numbers of 2 rows and 10 columns.

2. Initialize arrays

 

Like simple variables, arrays can be initialized when declared. The initializer for objects of composite types (such as an array) consists of a comma-separated list of initializers enclosed in curly braces. Each initializer in the list is either a constant of the corresponding type or, in turn, a list of initializers. This construct is used to initialize multidimensional arrays.

Having a list of initializers in the array declaration allows you not to specify the number of elements by its first dimension. In this case, the number of elements in the initializer list determines the number of elements by the first dimension of the array. This determines the amount of memory required to store the array. It is necessary to specify the number of elements for other dimensions of the array, except for the first one.

If there are fewer elements in the initializer list than in the array, the remaining elements are implicitly initialized with zero values. If the number of initializers is greater than required, an error message is displayed.

Examples of array initialization

int a[3] = {0, 1, 2};The number of initializers is equal to the number of elements
double b[5] = {0.1, 0.2, 0.3};The number of initializers is less than the number of elements
int c[ ] = {1, 2, 4, 8, 16};The number of array elements is determined by the number of initializers
int d[2][3] = {{0, 1, 2},
{3, 4, 5}};
Initialize a two-dimensional array. The array consists of two strings, // each with 3 elements. The elements of the first line // receive values 0, 1, and 2, and the second line receives values of 3, 4, and 5.
int e[3] = {0, 1, 2, 3};Error – number of initializers greater than number of elements

Note that there is no array assignment that corresponds to the initialization method described above.

int a[3] = {0, 1, 2};Declaration and initialization
a = {0, 1, 2};Error

3. Working with arrays

3.1. Accessing an Array Element

To access a specific element of an array, so-called index expressions are used:
<the name of the array>[<integer expression>]

Here, square brackets are a requirement of language syntax, not a sign of an optional construction.

An array index can be not only a constant, but also an expression that has an integer type, for example, [ + 1] (here it must be the name of the previously declared array, but also a variable of an integer type). aiai

The array declaration and the index expression used to access the array element have similar syntax. They differ in place in the program. This is especially important when we determine the index of the last element of the array. As mentioned earlier, the indexes of array elements in C start at 0, and the number of the last element is 1 less than the number of elements in the array. Therefore, if you declare an array of 10 elements, you cannot write an index expression [10], because in this case you are trying to access an element with an index of 10 that is not in your array. The compiler will not generate error messages, but the results of such a program will be unpredictable. xx

The name of the array is the address of its beginning! It is of type constant pointer to <type of array elements>. The construction [] is equivalent to *(a + i) (see lecture 5).ai

For a multidimensional array, specify the appropriate number of indexes in square brackets.

3.2. Array Processing

 

To process array elements, the for step loop operator is typically used.

for (i = 0;Set the cycle counter to the index value of the first element
i < n;Loop continuation condition – as long as the counter value is less than the number of elements in the array
i++)Increment the cycle counter by 1 to move to the next element of the array
< cycle body>In the body of the loop, one element of the array is processed

To process a multidimensional array, the appropriate number of cycles is used.

Arrays are not self-sufficient in the sense that it is not guaranteed that information about the number of elements will be stored along with the array itself. Most C++ implementations do not have index range validation for arrays. This is the traditional low-level approach to arrays. A more advanced concept of an array can be implemented using classes.

In C++, arrays are closely related to pointers. You can use the name of an array as a pointer to its first element. The value of the pointer to the element following the last element in the array is guaranteed to be meaningful. This is important for many algorithms. But because such a pointer does not actually point to any element in the array, it cannot be used for either reading or writing. The result of obtaining the address of the array element preceding the first is not determined, and such an operation should be avoided.

Implicitly converting an array name to a pointer to its first element is widely used in function calls.

int f(..., int x[], ...) { ... } int f(..., int *x, ...) { ... } void main() { int a[10]; ...You can use either of two options
f(..., a, ...); ... }Pass an array pointer to the f function a

Implicitly converting an array to a pointer when a function is called results in the loss of information about the size of the array. The function being called must determine this size in some way in order to perform meaningful actions.

When you declare a multidimensional array as a function parameter, you can omit only the first dimension.

int g(..., int x[][10], ...) { ... }The second and subsequent dimensions are mandatory

This restriction can be circumvented if you wish. However, other problems arise (see example 3 at the end of the lecture).

3.3. Array I/O

 

In C, it is not possible to enter and output an entire array with a single I/O statement. You can enter and output only one element of an array. Therefore, in order to enter the entire array, you must use a loop.

int a[10], n; printf("Enter the number of elements in the array (from 0 to 9): ");Declare an array and a variable for the number of elements in the array
scanf("%d", &n);Enter the number of elements in an array
if (n < 0 || n > 9) { printf("The number of elements in an array must be from 0 to 9!\n"); return; }If the input data is incorrect, // then print the corresponding message and exit the program
for (i = 0; i < n; i++)Enter an array one element at a time
scanf("%d", &a[i]);// You can use scanf("%d", a + i)

Withdrawal is also carried out in a cycle.

for (i = 0; i < n; i++) printf("a[%d] = %3d\n", i + 1, a[i]); 

As a result, we will see the following text on the screen: a[1] = 4 a[2] = 15 a[3] = -2 ...

3.4. Example 1. Processing a one-dimensional array

 

Three arrays of different dimensions are given. Determine in which array the sum of the elements is greater.

 

 #include <cstdio>
#include <locale.h>

const int nmax = 100;
  
int ArrayInput(int *n, double x[], char *fname); // Function for inputting an array from a file
double Sum(double x[], int n); // Function for finding the sum of array elements
  
void main(int argc, char *argv[])
 { double a[nmax], b[nmax], c[nmax];
   double sa, sb, sc, max;
   intna, nb, nc;

   setlocale(LC_ALL, "rus"); // Change the encoding for the console application

   if (argc < 4)
    { printf("Not enough parameters!\n");
      return;
     }
   if (!ArrayInput(&na, a, argv[1]))
     return;
   if (!ArrayInput(&nb, b, argv[2]))
     return;
   if (!ArrayInput(&nc, c, argv[3]))
     return;

   sa = Sum(a, na);
   sb = Sum(b, nb);
   sc = Sum(c, nc);

   max = sa;
   if (sb > max) max = sb;
   if (sc > max) max = sc;

   if (sa == max)
     printf("Array A has the maximum sum of elements: %9.3lf\n", max);
   if (sb == max)
     printf("Array B has a maximum sum of elements: %9.3lf\n", max);
   if (sc == max)
     printf("Array C has a maximum sum of elements: %9.3lf\n", max);
  }

double Sum(double x[], int n)
 { double s = 0;

   for (int i = 0; i < n; i++)
    s += x[i];

   return s;
  }

int ArrayInput(int *n, double x[], char *fname)
 { FILE *file;

   if ((file = fopen(fname, "r")) == NULL)
    { printf("Unable to open file '%s'\n", fname);
      return 0;
     }
   if (fscanf(file, "%d", n) < 1)
    { printf ("Error reading from file '%s'\n", fname);
      fclose(file);
      return 0;
     }
   if (*n < 0 || *n > nmax)
    { printf("Number of array elements must be between 1 and %d! (file '%s')\n", nmax, fname);
      return 0;
     }
   for (int i = 0; i < *n; i++)
    if (fscanf(file, "%lf", &x[i]) < 1)
     { printf ("Error reading from file '%s'\n", fname);
       fclose(file);
       return 0;
      }
   fclose(file);
   return 1;
  }

 

3.5. Example 2. Two-dimensional array processing

For each row of the matrix, check for null elements.

The first way

 

 


#include <cstdio>
#include <locale.h>

const int nmax = 100;
  
void Zeros(double x[][nmax], int m, int n, int z[]); // The Zeros function forms a one-dimensional array,
                                                         // i-th element of which is equal to 1,
                                                         // if there are zero elements in the i-th row, and 0 otherwise

void main(int argc, char *argv[])
 { double a[nmax][nmax];
   int m, n, z[nmax];
   FILE *file;

   setlocale(LC_ALL, "rus");
   if (argc < 2)
    { printf("Not enough parameters!\n");
      return;
     }
   if ((file = fopen(argv[1], "r")) == NULL)
    { printf("Unable to open file '%s'\n", argv[1]);
      return;
     }
   if (fscanf(file, "%d%d", &m, &n) < 2)
    { printf ("Error reading from file '%s'\n", argv[1]);
      fclose(file);
      return;
     }
   if (m < 0 || m > nmax || n < 0 || n > nmax)
    { printf("The number of rows and columns of the matrix must be between 1 and %d!\n", nmax);
      return;
     }
   for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
     if (fscanf(file, "%lf", &a[i][j]) < 1)
      { printf ("Error reading from file '%s'\n", argv[1]);
        fclose(file);
        return 0;
       }
   fclose(file);

   Zeros(a, m, n, z);
    
   for (int i = 0; i < m; i++)
    if (z[i])
     printf("There are zero elements in %3d line\n", i + 1);
  }

void Zeros(double x[][nmax], int m, int n, int z[])
 {int i, j;

   for (i = 0; i < m; i++)
    for(z[i] = 0, j = 0; j < n; j++)
     if (x[i][j] == 0)
      { z[i] = 1; break; }
  }

 

The second way

 

#include <cstdio>
#include <locale.h>

const int nmax = 100;
  
int Zeros(double x[], int n); // The Zeros function processes one row of the matrix and returns 1,
                                            // if there are zero elements in the string, and 0 otherwise
  
void main(int argc, char *argv[])
 { double a[nmax][nmax];
   int m, n;
     ... // Matrix entry (as in the first option)
   for (int i = 0; i < m; i++) // Construction a[i] (a is a two-dimensional array)
    if (Zeros(a[i], n)) // allows you to pass one row of a two-dimensional array to the function
     printf("There are zero elements in %3d line\n", i + 1);
  }

int Zeros(double x[], int n)
 { for (int j = 0; j < n; j++)
    if (x[j] == 0)
     return 1;
   return 0;
  }

3.6. Example 3. Summation of matrix elements

Two matrices of different sizes are given. The Sum function finds the sum of the elements of the matrix, regardless of the fact that the matrices have different numbers of columns. Note that the function will return a valid result only if all declared matrix elements are used.

 

#include <cstdio>
#include <locale.h>

double Sum(double *x, int m, int n);

void main(int argc, char *argv[])
 { const int na = 4, mb = 3, nb = 5;
   double a[na][na], b[mb][nb];
   double sa, sb;
   FILE *file;

   setlocale(LC_ALL, "rus");
   if (argc < 3)
    { printf("Not enough parameters!\n");
      return;
     }
     
   if ((file = fopen(argv[1], "r")) == NULL)
    { printf("Unable to open file '%s'\n", argv[1]);
      return;
     }

   for (int i = 0; i < na; i++)
    for (int j = 0; j < na; j++)
     if (fscanf(file, "%lf", &a[i][j]) < 1)
      { printf ("Error reading from file '%s'\n", argv[1]);
        fclose(file);
        return;
       }
   fclose(file);

   if ((file = fopen(argv[2], "r")) == NULL)
    { printf("Unable to open file '%s'\n", argv[2]);
      return;
     }

   for (int i = 0; i < mb; i++)
    for (int j = 0; j < nb; j++)
     if (fscanf(file, "%lf", &b[i][j]) < 1)
      { printf ("Error reading from file '%s'\n", argv[2]);
        fclose(file);
        return;
       }
   fclose(file);

   sa = Sum(a[0], na, na); // a[0] - pointer to the first row of the matrix
                                                        // (and, accordingly, to the beginning of the entire matrix).
   sb = Sum(reinterpret_cast<double *>(b), mb, nb); // Transform without checking with reinterpret_cast.
                                                        // You can't just write b - it will cause a message
                                                        // about the impossibility of converting a matrix into a pointer.

   printf("SumA = %6.2lf\nSumB = %6.2lf\n", sa, sb);
  }

double Sum(double *x, int m, int n)
 { double s = 0;

   for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++)
     s += x[i * n + j];

   return s;
  }