Write a program to convert a matrix to sparse matrix in C++?

In C++, a sparse matrix can be represented using an array of structures, where each structure stores the row, column, and value of a non-zero element in the matrix. Here's a program that converts a matrix to a sparse matrix: 

 

#include 
using namespace std;

const int MAX_SIZE = 100;

struct Element {
    int row, col, value;
};

int main() {
    int matrix[MAX_SIZE][MAX_SIZE], n, m;
    Element sparse[MAX_SIZE*MAX_SIZE];
    int sparseSize = 0;

    // Read input matrix
    cout << "Enter number of rows and columns: ";
    cin >> n >> m;
    cout << "Enter matrix elements:\n";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> matrix[i][j];
        }
    }

    // Convert to sparse matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] != 0) {
                sparse[sparseSize].row = i;
                sparse[sparseSize].col = j;
                sparse[sparseSize].value = matrix[i][j];
                sparseSize++;
            }
        }
    }

    // Print sparse matrix
    cout << "Sparse matrix representation:\n";
    for (int i = 0; i < sparseSize; i++) {
        cout << sparse[i].row << " " << sparse[i].col << " " << sparse[i].value << "\n";
    }

    return 0;
}

In this program, we first read the input matrix from the user. Then, we iterate over all elements of the matrix, and for each non-zero element, we add an element to the sparse matrix array. Finally, we print the sparse matrix representation by iterating over the sparse matrix array.

Submit Your Programming Assignment Details