In C++, arrays are used to store a collection of elements of the same data type. Arrays can be one-dimensional or multi-dimensional, and their elements can be accessed using their index. Here’s an overview of how to work with one-dimensional and multi-dimensional arrays in C++:
1. One-dimensional arrays: A one-dimensional array is a collection of elements of the same data type, all stored in a contiguous block of memory. The elements of a one-dimensional array can be accessed using their index, which starts at 0 for the first element. Here is an example of how to declare and work with a one-dimensional array:
int arr[5]; // declare an array of 5 integers for (int i = 0; i < 5; i++) { arr[i] = i; // assign values to array elements } for (int i = 0; i < 5; i++) { cout << arr[i] << " "; // output: 0 1 2 3 4 }
In this example, an array of 5 integers is declared and initialized with values from 0 to 4 using a for loop.
2. Multi-dimensional arrays: A multi-dimensional array is an array that contains one or more arrays as its elements. Multi-dimensional arrays can be two-dimensional, three-dimensional, or even higher-dimensional. The elements of a multi-dimensional array can be accessed using multiple indices. Here is an example ofhow to declare and work with a two-dimensional array:
int matrix[3][3]; // declare a 3x3 matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matrix[i][j] = i + j; // assign values to matrix elements } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << matrix[i][j] << " "; // output: 0 1 2 1 2 3 2 3 4 } cout << endl; }
In this example, a 3x3 matrix is declared and initialized with values that are the sum of their row and column indices, using nested for loops.
Arrays are a powerful tool in C++ that allows you to store and manipulate collections of elements of the same data type. By using one-dimensional and multi-dimensional arrays, you can write more efficient and concise code for a wide range of applications.