In this tutorial, we will write a program to check for the binary number in C.
What is a Binary Number?
A binary number is a number expressed in the base-2 numeral system that is the number that contains 2 symbols to represent all the numbers. The symbols are 0 and 1.
For example: 101011, 110011110, 10001111 are binary numbers.
C Program to check whether a Number is Binary or Not
We have used the while loop to iterate through the entered number in the program below. The program takes the input of a number from the user.
With each iteration, there is an if condition to check for 1 and 0 in the digit, If it is not 1 or 0 then it is not a binary number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <stdio.h> #include <conio.h> int main() { int i, number; printf("Enter the Number: "); scanf("%d", &number); int temp = number; while (number > 0) { i = number % 10; if (i != 0 && i != 1) { printf("%d is not a binary number", temp); break; } number /= 10; if (number == 0) { printf("%d is a binary number", temp); } } getch(); return 0; } |
Output:
Enter the Number: 1101
1101 is a binary number