Saturday, January 21

Convert Decimal Number to Binary Equivalent Using Linked list - C




Hi friends,


          In this post I'll explain "how  to convert a decimal number to binary equivalent using Linked list". Usually, we use array for this purpose, but arrays are created statically and memory wastage  may occur. Linked list is a  perfect solution for this as it is created dynamically and no there is no wastage of memory also.!!!!






Algorithm




  1. Initialize PREV_NODE and NODE as NULL.
  2. Input a number 'num'.
  3. if num<=0 go to step 9
  4. PREV_NODE=NODE
  5. add (num%2) to NODE->number
  6. NODE->next=PREV_NODE
  7. num=num/2
  8. go to step 3
  9. if NODE is NULL go to 13
  10. print NODE->number
  11. NODE=NODE->next 
  12. go to step 9
  13. End






The complete code in C is given here:




#include<stdio.h>


struct binary {
       int num;
       struct binary *next;
       };


struct binary* add( struct binary **curr, int n)
 {
  
   struct binary *temp;
   temp=(struct binary *)malloc(sizeof(struct binary));
   temp->num=n;
   temp->next=*curr;
   return temp;
      
 }
       


int main()
{
     int number, binary_num;
     struct binary *head= NULL;
     printf("ENTER A DECIMAL NUMBER  :   ");
     scanf("%d",&number);
     
     while(number>0)
     {
     binary_num=number%2;
     head =add(&head,binary_num);
     number/=2;
     }
  printf("EQUIVALENT BINRY NUMBER IS   :   ");  
  for(;head!=NULL;head=head->next)
     printf("%d",head->num);


}










Friends, I hope this post will be useful to you..!!!
Your valuable suggestions are always welcomed..!!!!Comment it here.!!


2 comments :

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

maan gaye ustaad

v!p!n said... Best Blogger Tips [Reply to comment] Best Blogger Templates

@Anonymous thank you for your feedback.. Keep visiting.!!!!!!

Post a Comment