Program to find binary equal of a decimal number |C Program|

Introduction

     Binary representation is a fundamental concept in computer science and programming. In this blog post, we'll explore a simple C program that converts a decimal number into its binary equivalent. Understanding how to perform such conversions is essential for anyone venturing into the world of computer programming.  

Code

    
     
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
        int n,i=0,b[20],j;
        clrscr();
        printf("enter the decimal number:");
        scanf("%d",&n);
        while(n>0)
        {
        b[i]=n%2;
        n=n/2;
        i++;
        }
        printf("equivalent binary is:");
        j=i-1;
        for(i=j;j>=0;j--)
        {
        printf("%d",b[j]);
        }
        getch();
    }
       
     


Output


    enter the decimal number:20
    equivalent binary is:10100        
       




Explanation

1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter a decimal number, and the input is stored in the variable n.
3. Decimal to Binary Conversion:
A while loop iterates through the decimal-to-binary conversion process.
In each iteration, the remainder of the division by 2 (n % 2) is stored in the array b, and n is updated by integer division by 2 (n / 2).
The array b holds the binary digits in reverse order.
4. Result Display:
The program prints the equivalent binary representation of the entered decimal number by iterating through the array b in reverse order.
5. User Interaction:
Users receive the binary representation of the entered decimal number.


Conclusion

     This C program showcases a simple yet powerful algorithm for converting decimal numbers into their binary equivalents. Understanding how binary representations work is fundamental in computer science, especially in the context of data storage and manipulation. Experiment with different decimal inputs, analyze the flow of the program, and consider modifications or optimizations. This exercise will strengthen your grasp of binary representation and pave the way for more advanced concepts in computer programming. Happy coding!

Post a Comment

0 Comments