How to declare and use 2-dimensional Arrays?
Example 1: int x[2][3] = {{4, 2, 3}, {9, 6, 7}}; Example 2: int x[3][4] = {{4, 2, 3, 9}, {9, 6, 7, 2}, {3, 4, 7, 8}};
2 Dimensional Arrays Program in C / C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<iostream> using namespace std; int main() { // an array with 3 rows and 2 columns. int x[3][2] = {{6,4}, {8,7}, {1,9}}; // Displaying of array element's value for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << "Element at x[" << i << "][" << j << "]: "; cout << x[i][j]<<endl; } } return 0; } |
Sum of two arrays using Two dimensional arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// C program to find the sum of two arrays #include <stdio.h> int main() { float array1[2][2], array2[2][2], array3[2][2]; // array1 have two rows and two collumn // array2 have two rows and two collumn // array3 have two rows and two collumn int i, j; // Taking input using nested for loop printf("Enter elements for array1 \n"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter a%d%d: ", i+1, j+1); scanf("%f", &array1[i][j]); } // Taking input using nested for loop printf("Enter elements for array2\n"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter b%d%d: ", i+1, j+1); scanf("%f", &array2[i][j]); } // adding corresponding elements of two arrays for(i=0; i<2; ++i) for(j=0; j<2; ++j) { Array3[i][j] = array1[i][j] + array2[i][j]; } // Displaying the sum printf("\n Overall Sum Of full Matrix is:"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("%.1f\t", array3[i][j]); if(j==1) printf("\n"); } return 0; } |
Comparison Between one and two Dimensional Array
1-DIMENSIONAL: Store a single list of elements. Store only similar elements with the same data type. 2-DIMENSIONAL: Store ‘list of lists’ or ‘array of arrays’ or ‘array of 1-dimensional arrays’. Comparison of Declaration Between one and two Dimensional Array 1-DIMENSIONAL: How to declare in C++? type variable_name[ size ]; 2-DIMENSIONAL: How to declare in C++. type variable_name[size1][size2]; Comparison of Receiving parameter Between one and two Dimensional Array 1-DIMENSIONAL: Parameters can be received in the followings;- sized array
- unsized array
- Pointer