1 Dimensional & 2 Dimensional
Lesson 5 of 26 in Coddy's Arrays in C++ course.
A One-Dimensional Array is the simplest Array in which the elements are stored linearly in a straight manner and can be accessed individually.
As we saw in the lesson types of arrays, we can create an array of any data type. Two Dimensional arrays are not different and they can populate one type of data. Each element inside the 2-D arrays is a 1-D array. 2-D arrays are also called a matrix (A mathematical term).
For example,
[[1,2,3],
[4,5,6],
[7,8,9]]
Here we can see that the first element is another array of size 3: [1,2,3].
To declare such an array, instead of giving the size linearly only, we have to allocate the memory considering columns and rows.
eg
int arr[m][n];
Here this array has 2 dimensions. m rows and n columns.
In order to populate the input values inside a 2-D array, we use a nested loop. The same thing goes with outputting the result.
//Input
int arr[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>arr[i][j];
}
}//Output
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cout<<arr[i][j]<<" ";
}
}Challenge
Input a matrix with m rows and n columns (Provided by the user) and output the elements of the matrix by adding 5 to each of its elements.
Try it yourself
#include<iostream>
using namespace std;
int main(){
//Write your code here
return 0;
}