Convert a Matrix into another Matrix of given dimensions | C ++ program to implement the above approach ; Function to construct a matrix of size A * B from the given matrix elements ; Initialize a new matrix ; Traverse the matrix , mat [ ] [ ] ; Update idx ; Print the resultant matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ConstMatrix ( int * mat , int N , int M , int A , int B ) { if ( N * M != A * B ) return ; int idx = 0 ; int res [ A ] [ B ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { res [ idx / B ] [ idx % B ] = * ( ( mat + i * M ) + j ) ; idx ++ ; } } for ( int i = 0 ; i < A ; i ++ ) { for ( int j = 0 ; j < B ; j ++ ) cout << res [ i ] [ j ] << " ▁ " ; cout << " STRNEWLINE " ; } } int main ( ) { int mat [ ] [ 6 ] = { { 1 , 2 , 3 , 4 , 5 , 6 } } ; int A = 2 ; int B = 3 ; int N = sizeof ( mat ) / sizeof ( mat [ 0 ] ) ; int M = sizeof ( mat [ 0 ] ) / sizeof ( int ) ; ConstMatrix ( ( int * ) mat , N , M , A , B ) ; return 0 ; }