Programming Interview Question for CSS

C# Program to Convert Decimal to Binary

 C# Program for Conversion of Decimal to Binary

                            In this article, I am going to explain how to convert a decimal number into a binary number: First, we need to know about the Decimal number, Binary Number
1.What is the Decimal Number?
2.What is the  Binary Number?

1.What is the Decimal Number?
                    Decimal Numbers are the numbers whose base is 10. That means the decimal numbers are in the ranges from (0 to 9). Any combination  of such digits (from 0 to 9) is considered as a decimal number like 2345,7654,7,5,4,9,231,etc.

The examples of decimal numbers are given below:


2.What is the Binary Number?
              Binary means basically two(2) that means either 1 or 0. It has a base is 2, based on these any combination of 0 and 1 is a binary number.The example for the binary numbers is 10,100,101,1000,01,111,1010,etc.
Here you can consider some  more examples like OFF(0), ON(1) & True(1)/False(0).Then now we will go for an example for the conversion of Decimal Number to Binary Number:
Algorithm for the conversion of Decimal to Binary Number:
Step1: First, divide the given  number by 2 through the modulus (%) operator and store the remainder in an array,
Step2:  Then Divide the number by 2 through the division (/) operator.
Step3: Repeat step 2 until the number is greater than zero.
 using System;  
 namespace DecimalToBinaryConversion  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.Write("Enter the Decimal Number : ");  
       int DecimalNumber = int.Parse(Console.ReadLine());  
       int i;  
       int[] numberArray = new int[10];  
       //This loop will execute untill the decimal Number will be Greter than Zero  
       for (i = 0; DecimalNumber > 0; i++)  
       {  
         //Modulus(%) will return the remainder of the given decimal number  
         numberArray[i] = DecimalNumber % 2;  
         //It will return the Quotient of the Decimal Number  
         DecimalNumber = DecimalNumber / 2;  
       }  
       Console.Write("Binary Represenation of the given Decimal Number is : ");  
       //This Loop Will display binary Number Upto given Decimal Number  
       for (i = i - 1; i >= 0; i--)  
       {  
         Console.Write(numberArray[i]);  
       }  
       Console.ReadLine();  
     }  
   }  
 }  
The output for the above  program is given below:
 Enter the Decimal Number : 10  
 Binary Represenation of the given Number : 1010  
Conclusion:-
             By using these Conversions concept we convert from  Decimal numbers to  Binary Number, Binary to Decimal, Hexadecimal to Decimal it will be useful for programming like conversions.


Comments