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.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.