Monday, December 30, 2013

Binary of a number: logic and program

Binary (Base 2) value of a number involves
1)dividing the number by 2 and storing the remainder in the array.
2)dividing the number by 2.
3)repeating the above steps until number becomes zero.
4)printing the array in reverse order.

taking number =5
index=0
number=5 (not equal to 0)
rev[index=0]=number%2=5%2=1
index=index+1=0+1=1
number=number/2=5/2=2

number=2(not equal to 0)
rev[index=1]=number%2=2%2=0
index=index+1=1+1=2
number=number/2=2/2=1

number=1 (not equal to zero)
rev[index=2]=number%2=1%2=1
index=index+1=2+1=3
number=number/2=1/2=0

number=0 (stop loop)

Print array in reverse order
for(i=index-1  ;i<=0;i--)
print a[i]
initially
i=3-1=1 a[2] is printed
i=2-1=1 a[1] is printed
i=1-1=0 a[0] is printed

#include<stdio.h>
int main()
{
           int i , index;
           unsigned long num, num_copy;
           int num_rev[20];

          /* taking size equal to 20 means it can store binary number of 20 places
             number upto 1024*1024 (2^20) can be entered by the user
            If this value is exceeded by user then there will be overflow in array
            This error will  not be reported as bound checking is not done automatically in C for arrays */
 
           printf("\nEnter a +ve number(less than 1048527:");
           scanf("%d",&num);
           num_copy=num;
         
           index=0;
           while(num_copy!=0)
           {
                       num_rev[index++]=num_copy%2;
                       num_copy=num_copy/2;
            }
           
            printf("\nBinary Equivalent of %d is ",num);
            for(i=index-1;i>=0;i--)
                  printf("%d",num_rev[i]);

return 0;
}
                      




No comments:

Post a Comment