ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES
Convert a Dense Matrix to Triplet Form
Learn how to convert a dense matrix to triplet form using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 5 1 0 2 1 3 7 2 2 3
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int matrix[3][4] = {{0, 5, 0, 0}, {2, 0, 0, 7}, {0, 0, 3, 0}};
for (int row = 0; row < 3; row++)
for (int column = 0; column < 4; column++)
if (matrix[row][column] != 0) printf("%d %d %d\n", row, column, matrix[row][column]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 5 1 0 2 1 3 7 2 2 3
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store only each non-zero value together with its row and column.
- Display the computed result.
Store only each non-zero value together with its row and column.
EFFICIENCY
Time and space complexity
Time complexity
O(rows * columns)
Auxiliary space
O(non-zero elements)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
