Write a program to read the elements of a sparse matrix from the user and display
it in its 3-tuple form. Your program should verify whether at the entire matrix
is sparse or not.
#include <iostream>
using namespace std;
int main()
{
int barMatrix[4][5] =
{
{0 , 0 , 2 , 0 , 4 },
{7 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 4 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (barMatrix[i][j] != 0)
size++;
int fooMatrix[3][size];
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (barMatrix[i][j] != 0)
{
fooMatrix[0][k] = i;
fooMatrix[1][k] = j;
fooMatrix[2][k] = barMatrix[i][j];
k++;
}
for (int i=0; i<3; i++)
{
for (int j=0; j<size; j++)
cout <<" "<< fooMatrix[i][j];
cout <<"\n";
}
return 0;
}
Comments
Leave a comment