Q1 sit exam.docx
Document Details
Uploaded by Deleted User
Full Transcript
**Q1. Write a C program to implement a sparse matrix.** \#include \ \#include \ // Structure to represent a non-zero element in the sparse matrix typedef struct Node { int row; int col; int value; struct Node\* next; } Node; // Structure to represent a sparse matrix typedef struct SparseM...
**Q1. Write a C program to implement a sparse matrix.** \#include \ \#include \ // Structure to represent a non-zero element in the sparse matrix typedef struct Node { int row; int col; int value; struct Node\* next; } Node; // Structure to represent a sparse matrix typedef struct SparseMatrix { Node\* head; int numRows; int numCols; } SparseMatrix; // Function to create a new sparse matrix SparseMatrix\* createSparseMatrix (int rows, int cols) { SparseMatrix\* matrix = (SparseMatrix\*)malloc(sizeof(SparseMatrix)); matrix-\>head = NULL; matrix-\>numRows = rows; matrix-\>numCols = cols; return matrix; } // Function to insert a non-zero element into the sparse matrix void insertElement(SparseMatrix\* matrix, int row, int col, int value) { if (value == 0) return; // Ignore zero values Node\* newNode = (Node\*)malloc(sizeof(Node)); newNode-\>row = row; newNode-\>col = col; newNode-\>value = value; newNode-\>next = matrix-\>head; matrix-\>head = newNode; } // Function to display the sparse matrix void displaySparseMatrix(SparseMatrix\* matrix) { printf(\"Sparse Matrix (Row, Column, Value):\\n\"); Node\* current = matrix-\>head; while (current) { printf(\"(%d, %d, %d)\\n\", current-\>row, current-\>col, current-\>value); current = current-\>next; } } // Function to free the sparse matrix void freeSparseMatrix(SparseMatrix\* matrix) { Node\* current = matrix-\>head; Node\* nextNode; while (current) { nextNode = current-\>next; free(current); current = nextNode; } free(matrix); } int main() { SparseMatrix\* matrix = createSparseMatrix(5, 5); // Inserting some non-zero elements insertElement(matrix, 0, 1, 10); insertElement(matrix, 1, 0, 20); insertElement(matrix, 3, 3, 30); insertElement(matrix, 4, 2, 40); // Display the sparse matrix displaySparseMatrix(matrix); // Free the allocated memory freeSparseMatrix(matrix); return 0; } **[OUTPUT:]** Sparse Matrix (Row, Column, Value): (4, 2, 40) (3, 3, 30) (1, 0, 20) (0, 1, 10)