Sparse Matrix Representation

This program represents a sparse matrix using triplet form.

Problem Statement

Write a Java program to represent a sparse matrix in triplet form (row, column, value).

Source Code

1 public class SparseMatrixRepresentation {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Sparse Matrix Representation");
4 int[][] A = {
5 {0,0,3},
6 {0,0,0},
7 {4,0,0}
8 };
9 System.out.println("Row Col Val");
10 for(int i=0;i<3;i++){
11 for(int j=0;j<3;j++){
12 if(A[i][j]!=0){
13 System.out.println(i+" "+j+" "+A[i][j]);
14 }
15 }
16 }
17 }
18 }

Program Output

Eduinq Sparse Matrix Representation
Row Col Val
0   2   3
2   0   4

Explanation

Sparse matrix has many zeros. - Triplet form stores only non zero values with row and column indices. - Nested loops check each element. - Together demonstrates sparse matrix representation. Conclusion: Demonstrates sparse matrix representation using triplet form.

Quick Links to Explore