Until now the arrays we discussed are one-dimensional arrays. C++ also supports storing data in multiple dimensions. A two-dimensional array can represent tabular data i.e., in rows and columns. Syntax for declaring a two-dimensional array is as follows:
type array-name[rows][coulumns];
We can initialize a two-dimensional array at the time of declaration itself as shown below:
int data[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
In the above statement, data is a two-dimensional array having three rows and three columns. We can imagine a two-dimensional array as an array of arrays. Consider the following program which demonstrates reading and displaying elements in a two-dimensional array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<iostream> using namespace std; int main() { int data[3][3]; cout << "Enter data for three rows and three columns: "; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cin >> data[i][j]; } } cout << "Elements in the array are: " << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << data[i][j] << " "; } cout << endl; } cout << endl; return 0; } |
Input and output for the above program is as follows:
1 2 3 4 5 6 7 8 9 10 | Enter data for three rows and three columns: 1 2 3 4 5 6 7 8 9 Elements in the array are: 1 2 3 4 5 6 7 8 9 |
Observe how nested for loops are used to read and print the array elements effectively.
Dynamic Arrays
Consider you are writing a program to store student records which are bound to increase over time. There is now way to assume the size of the array before hand. In such cases static arrays are a bad choice. Instead, use dynamic arrays.
Dynamic arrays can be created in C++ programs using vector class which is available in the header file vector. Since vector uses template syntax and they are not at discussed, let’s look at a program which demonstrates creating and using a vector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<iostream> #include<vector> using namespace std; int main() { vector < int > nums(3); nums[0] = 1; nums[1] = 2; nums[2] = 3; cout << "Size of the array is: " << nums.size() << endl; cout << "Enter a number to store in the array: "; int n; cin >> n; nums.push_back(n); cout << "New size of the array is: " << nums.size() << endl; return 0; } |
Input and output for the above program is as follows:
1 2 3 4 5 | Size of the array is: 3 Enter a number to store in the array: 10 New size of the array is: 4 |
In the above program, size() function returns the size of the vector (array) and push_back() function inserts the given element at the end of the vector (array).
Take your time to comment on this article.