Name : Vanshika Rajput
E.No : 00289902722
PROGRAM - 1
AIM : Implement sparse matrix using array. Description of program:
a. Read a 2D array from the user. b. Store it in the sparse matrix form, use array of structures. c. Print the final
array.
ALGORITHM :
Step 1 : Start
Step 2 : Define Structures - Define a structure Element with attributes row, col, and value. Define a structure
SparseMatrix with attributes rows, cols, numElements, and an array of Element.
Step 3 : Read Matrix - Prompt user for the number of rows and columns (rows and cols). Read elements into a 2D
matrix matrix[rows][cols].
Step 4 : Create Sparse Matrix -
Initialize SparseMatrix sparse.
Set sparse.rows and sparse.cols to rows and cols.
Initialize sparse.numElements to 0.
Iterate through each element in matrix:
If the element is non-zero:
Store its row, col, and value in sparse.data[].
Increment sparse.numElements.
Step 5 : Print Sparse Matrix -
Display sparse.rows and sparse.cols.
Display non-zero elements' row, col, and value from sparse.data[].
Step 6 : Stop
CODE :
#include <stdio.h>
#define MAX_SIZE 100
struct Element {
int row, col, value;
};
Name : Vanshika Rajput
E.No : 00289902722
struct SparseMatrix {
int rows, cols, numElements;
struct Element data[MAX_SIZE];
};
void createSparseMatrix(int matrix[][MAX_SIZE], int rows, int cols, struct SparseMatrix *sparse) {
sparse->rows = rows;
sparse->cols = cols;
sparse->numElements = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] != 0) {
sparse->data[sparse->numElements++] = (struct Element){i, j, matrix[i][j]};
}
}
}
}
void printSparseMatrix(struct SparseMatrix sparse) {
printf("Sparse Matrix Representation:\n");
printf("Rows: %d, Columns: %d\n", sparse.rows, sparse.cols);
printf("Non-zero elements:\n");
printf("Row Col Value\n");
for (int i = 0; i < sparse.numElements; ++i) {
printf("%3d %3d %5d\n", sparse.data[i].row, sparse.data[i].col, sparse.data[i].value);
}
}
int main() {
int rows, cols;
printf("Enter the number of rows and columns for the matrix: ");
scanf("%d %d", &rows, &cols);
int matrix[MAX_SIZE][MAX_SIZE];
printf("Enter the elements of the %dx%d matrix:\n", rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
scanf("%d", &matrix[i][j]);
}
}
Name : Vanshika Rajput
E.No : 00289902722
struct SparseMatrix sparse;
createSparseMatrix(matrix, rows, cols, &sparse);
printSparseMatrix(sparse);
return 0;
}
OUTPUT :