Efficient method to store a Lower Triangular Matrix using Column | C ++ program for the above approach ; Dimensions of the matrix ; Structure of a memory efficient matrix ; Function to set the values in the Matrix ; Function to store the values in the Matrix ; Function to display the elements of the matrix ; Traverse the matrix ; Function to generate an efficient matrix ; Declare efficient Matrix ; Initialize the Matrix ; Set the values in matrix ; Return the matrix ; Driver Code ; Given Input ; Function call to create a memory efficient matrix ; Function call to print the Matrix
#include <bits/stdc++.h> NEW_LINE #include <stdio.h> NEW_LINE using namespace std ; const int N = 5 ; struct Matrix { int * A ; int size ; } ; void Set ( struct Matrix * m , int i , int j , int x ) { if ( i >= j ) m -> A [ ( ( m -> size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] = x ; } int Get ( struct Matrix m , int i , int j ) { if ( i >= j ) return m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] ; else return 0 ; } void Display ( struct Matrix m ) { for ( int i = 1 ; i <= m . size ; i ++ ) { for ( int j = 1 ; j <= m . size ; j ++ ) { if ( i >= j ) cout << m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] << " ▁ " ; else cout << "0 ▁ " ; } cout << endl ; } } struct Matrix createMat ( int Mat [ N ] [ N ] ) { struct Matrix mat ; mat . size = N ; mat . A = ( int * ) malloc ( mat . size * ( mat . size + 1 ) / 2 * sizeof ( int ) ) ; for ( int i = 1 ; i <= mat . size ; i ++ ) { for ( int j = 1 ; j <= mat . size ; j ++ ) { Set ( & mat , i , j , Mat [ i - 1 ] [ j - 1 ] ) ; } } return mat ; } int main ( ) { int Mat [ 5 ] [ 5 ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 2 , 0 , 0 , 0 } , { 1 , 2 , 3 , 0 , 0 } , { 1 , 2 , 3 , 4 , 0 } , { 1 , 2 , 3 , 4 , 5 } } ; struct Matrix mat = createMat ( Mat ) ; Display ( mat ) ; return 0 ; }