TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sparse_matrix.cpp File Reference
#include <iostream>
Include dependency graph for sparse_matrix.cpp:

Go to the source code of this file.

Functions

int main ()
 

Detailed Description

A sparse matrix is a matrix which has number of zeroes greater than \(\frac{m\times n}{2}\), where m and n are the dimensions of the matrix.

Definition in file sparse_matrix.cpp.

Function Documentation

◆ main()

int main ( void )

main function

Definition at line 9 of file sparse_matrix.cpp.

9 {
10 int m, n;
11 int counterZeros = 0;
12
13 std::cout << "Enter dimensions of matrix (seperated with space): ";
14 std::cin >> m;
15 std::cin >> n;
16
17 int **a = new int *[m];
18 for (int i = 0; i < m; i++) a[i] = new int[n];
19
20 std::cout << "Enter matrix elements:";
21 std::cout << "\n";
22
23 // reads the matrix from stdin
24 for (int i = 0; i < m; i++) {
25 for (int j = 0; j < n; j++) {
26 std::cout << "element? ";
27 std::cin >> a[i][j];
28 }
29 }
30
31 // counts the zero's
32 for (int i = 0; i < m; i++) {
33 for (int j = 0; j < n; j++) {
34 if (a[i][j] == 0)
35 counterZeros++; // Counting number of zeroes
36 }
37 }
38
39 // makes sure the matrix is a sparse matrix
40 if (counterZeros > ((m * n) / 2)) // Checking for sparse matrix
41 std::cout << "Sparse matrix";
42 else
43 std::cout << "Not a sparse matrix";
44
45 for (int i = 0; i < m; i++) delete[] a[i];
46 delete[] a;
47 return 0;
48}