Page 324 - Cs_withBlue_J_C11_Flipbook
P. 324

Program 2      Using the concept of 1 dimensional array, write a program in Java to accept a decimal number
                               and convert it into its binary equivalent. Display the binary equivalent number.

                1       import java.util.*;

                2       class convert_dec_bin
                3       {

                4           public static void main()
                5           {

                6               Scanner sc= new Scanner(System.in);
                7               int i, j=0, rem, num, temp, bin=0;

                8               int binarr[ ]=new int[20];
                9               System.out.print("Enter a number in decimal: ");

                10              num = sc.nextInt();
                11              temp=num;

                12              for(;temp>0;temp=temp/2,j++)
                13              {

                14                  rem=temp%2;
                15                  binarr[j]=rem;

                16              }
                17              for(i=j-1;i>=0;i--)

                18              {
                19                  bin=bin*10+binarr[i];

                20              }
                21              System.out.println(" Decimal Number: "+ num);
                22              System.out.println(" Binary Number: "+ bin);

                23          }

                24      }
              The output of the preceding program is as follows:
              Output 1:
              Enter a number in decimal: 24
              Decimal Number: 24
              Binary Number: 11000
              Output 2:
              Enter a number in decimal: 200
              Decimal Number: 200
              Binary Number: 11001000





                322322  Touchpad Computer Science-XI
   319   320   321   322   323   324   325   326   327   328   329