Practice Program







  • Program of Converting Decimal to binary.
  • Solution: through While loop
    void main()
    {
        int i,j=0,n;
        int a[30];
    
        printf("Enter the decimal number:");
        scanf("%d",&n);
    
    
        while(n!=0)
        {
            a[j] = n%2;//storing the remainder at every iteration as element in an array
            n = n/2;//at every iteration we are dividing 'n' with 2
               //and storing its quotient as a new value in of  'n' variable.
         j++;
        }
         j = j-1;
         printf("Number in Binary form: ");
        while(j>=0) //printing the binary form of  a number. 
        {
            printf("%d",a[j]);
            j--;
        }
    
    }
    

    Output1
    Enter the decimal number: 12

    Number in Binary form: 110

    Output2
    Enter the decimal number: 32

    Number in Binary form: 10000

    Output3
    Enter the decimal number: 44

    Number in Binary form: 10110




    Solution: from do-while loops
    void main()
    {
        int i,j=0,n;
        int a[30];
    
        printf("Enter the decimal number:");
        scanf("%d",&n);
    
    
       do
        {
            a[j] = n%2;//storing the remainder at every iteration as element in an array
            n = n/2;//at every iteration we are dividing 'n' with 2
               //and storing its quotient as a new value in of  'n' variable.
         j++;
        }while(n!=0);
         j = j-1;
         do
        //printing the binary form of  a number. 
        {
            printf("%d",a[j]);
            j--;
        }while(j>=0);
    
    }
    





    defining a function 'do_binary' which will print decimal number in a binary form.
    void do_binary(int n)
    {
         int j=0;
        int a[10];
    
    
    
    
        while(n!=0)
        {
            a[j] = n%2;//storing the remainder at every iteration as element in an array
            n = n/2;//at every iteration we are dividing 'n' with 2
               //and storing its quotient as a new value in of  'n' variable.
         j++;
        }
         j = j-1; //decrementing the value of j by 1,
            //because at current j value there is a garbage value.
    
        while(j>=0)
        {
            printf("%d",a[j]);
            j--;
        }
    }
    

    Using above define function 'do_binary()':
    void main()
    {
    printf("Number in Binary form: ");
    do_binary(12);
    }
    

    Output1
    Number in Binary form: 110

    Using above define function 'do_binary()':
    void main()
    {
    printf("Number in Binary form: ");
    do_binary(32);
    }
    

    Output2
    Number in Binary form: 10000

    Using above define function 'do_binary()':
    void main()
    {
    printf("Number in Binary form: ");
    do_binary(44);
    }
    

    Output3
    Number in Binary form: 10110