Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check if a matrix is Binary matrix or not in C++
A binary matrix is a matrix whose all elements are binary values i.e., 0 or 1. Binary matrix can be also called Boolean matrix, Relational Matrix, Logical matrix.
Given below the example
$$\begin{bmatrix} 0 & 1 & 0
\ 1 & 1 & 0
\ 1 & 0 & 1
\ \end {bmatrix}\:\:\:\:\:\:\:\:\:
\begin{bmatrix}
0 & 3 & 0
\ 1 & 1 & 0
\ 1 & 0 & 2
\ \end{bmatrix}\\tiny This\:is\:a\:Binary\:Matrix\:\:\:\:\:\:\:
This\:is\:not\:a\:binary\:matrix$$
In Above figure first matrix on the left is a Binary matrix, the other matrix there are some values which are not Binary(0 or 1) are highlighted in red i.e., 3 and 2 hence that is not a binary matrix.
Example
Input: m[4][3] = { { 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 1, 1, 0, 0 } }
Output: its a binary matrix
Approach
We can traverse the whole matrix and check all the elements if 0 or 1 then print it is a binary matrix, else print it is not binary matrix.
Algorithm
Start
Step 1 -> define macros as #define row 3 and #define col 4
Step 2 -> Declare function to check if a matrix is binary matrix or not
bool check(int arr[][col])
Loop For int i = 0 and i < row and i++
Loop For int j = 0 and j < col and j++
IF(!(arr[i][j] = 0 || arr[i][j] = 1))
return false
End
End
End
return true
step 3 -> In main()
Declare an array as int arr[row][col] = { { 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 1, 1, 0, 0 } }
If (check(arr))
Print its a binary matrix
Else
Print its not a binary matrix
Stop
Example
#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 4
//check if a matrix is binary matrix or not
bool check(int arr[][col]){
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
if (!(arr[i][j] == 0 || arr[i][j] == 1))
return false;
}
}
return true;
}
int main(){
int arr[row][col] = { { 0, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 1, 1, 0, 0 } };
if (check(arr))
cout << "its a binary matrix";
else
cout << "its not a binary matrix";
return 0;
}
Output
its a binary matrix