C program to convert the given decimal number to its binary equivalent.

 


Program:

/* c program to convert the given decimal number into its binary equivalent. */
#include<stdio.h>
#define SIZE 80
struct stack{                      /*   defining a structure for stack    */
    int line[SIZE];
 int top;                       /* top index of stack  */
 };
void push(struct stack*, int);
int pop(struct stack*);
int main()
{
        struct stack s;  
        s.top=-1;                /* initializing  empty stack i.e, top index=-1 */
        int num;
        int rem,temp;
        printf("Decimal number to be converted: ");
        scanf("%d",&num);
        if(num==0)
            printf("%d",num);
        while(num>0)  /* while num>0, divide the number by 2 and store the remainder in stack  */
        {
               rem=num%2;
               push(&s,rem);
               num=num/2; 
        }
        printf("Binary number: ");
        while(s.top!=-1)        /* while stack is not empty */
        {
               temp=pop(&s);
               printf("%d ",temp);
        }
         return 0;
}
void push(struct stack *ps, int x)      /* function to push, ps is pointer to stack */
{
       if((ps->top)==SIZE-1)                /* if no more element can be accommodated */
      {
              printf("stack overflow");
              return;
      }
      int a=++(ps->top);                   /* increment top index   */
      ps->line[a]=x;                       /* push the element onto stack */
      return;
}
int pop(struct stack* ps)
{
       if(ps->top==-1)                        /* if stack is empty */
      {
             printf("stack underflow");
             return;
      }
      int x=(ps->line[(ps->top)]);           /* pop the value from the top of stack */
      (ps->top)--;                           /* decrement top index of stack   */
      return x;
}

Sample input and output:

Decimal number to be converted: 100
Binary number: 1 1 0 0 1 0 0
 
Now you can do some changes in the code to write the code for decimal to octal conversion.

No comments: