Convert decimal To Binary with stack - C Data Structure

C examples for Data Structure:Stack

Description

Convert decimal To Binary with stack

Demo Code

#include <stdio.h>
#include <stdlib.h>

typedef struct {
  int bit;/* w ww.j  a  v a2s .  c  o  m*/
} StackData;

#define Error -9999

typedef struct node {
  int num;
  struct node *next;
} Node, *NodePtr;

typedef struct stackType {
  NodePtr top;
} StackType, *Stack;

Stack initStack() {
  Stack sp = (Stack)malloc(sizeof(StackType));
  sp->top = NULL;
  return sp;
}

int empty(Stack S) {
  return (S->top == NULL);
}

void push(Stack S, int n) {
  NodePtr np = (NodePtr)malloc(sizeof(Node));
  np->num = n;
  np->next = S->top;
  S->top = np;
}

int pop(Stack S) {
  if (empty(S))
    return Error;

  int hold = S->top->num;

  NodePtr temp = S->top;

  S->top = S->top->next;

  free(temp);

  return hold;
}

int main() {
  StackData temp;

  int n;

  Stack S = initStack();

  printf("Enter a positive integer: ");

  scanf("%d", &n);

  while (n > 0) {

    temp.bit = n % 2;

    push(S, temp.bit);

    n = n / 2;

  }

  printf("\nIts binary equivalent is ");

  while (!empty(S))
    printf("%d", pop(S));

  printf("\n");
}

Related Tutorials