In: Computer Science
[PLEASE USE C++] Write a function to read values of a number of rows, number of columns, 2 dimensional (2D) array elements and display the 2D array in a matrix form. Input 2 3 1 4 5 2 3 0 Where, First line of represents the number of rows. Second line of input represents the number of columns. Third line contains array elements of the 1st row and so on. Output 1 4 5 2 3 0 where There must be single space between 2 numbers in the row. There should not be any space after the last number in the row. e.g. in the 2nd row, there should not be any space after number 0. Assume that, Row and column values are integers within the range [1 to 100]. 2D Array elements are within the range [-2147483648 t o 2147483647].
The code snippet for the question provided is provided below:
#include<iostream>
using namespace std;
int main()
{
int r, c, i, j;
cin>>r;
cin>>c;
int matrix[r][c];
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
cin>>matrix[i][j];
}
}
cout<<"\nThe Matrix representation of 2D array :\n";
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
In this program the integer variables declared are r, c, i ,j and 2D array matrix[][].
r variable denotes the rows in the matrix
c variable denotes the columns in the matrix.
i and j are used to loop through different indices in the matrix.
The first for loop block is to insert the values into the 2D array.
And the second for loop block was to print the 2D array in matrix form
The screenshot of the program after running and the ouput generated are attached for your reference:
The IDE used to code is codeBlocks.
The screenshots of ouput generated by providing the values given in the question are:
Hope this helps!!!