c program for decimal to binary using stack

Solutions on MaxInterview for c program for decimal to binary using stack by the best coders in the world

showing results for - "c program for decimal to binary using stack"
Ana Paula
26 Sep 2018
1/*  C Program to convert decimal to binary using stack  */
2
3#include<stdio.h>
4#include<stdlib.h>
5#define MAX 50
6
7int isEmpty(int top, int stack_arr[]);
8void push(int x, int *top, int stack_arr[]);
9int pop(int *top, int stack_arr[]);
10void DecToBin(int num);
11
12int main()
13{
14        int num;
15        printf("Enter an integer : ");
16        scanf("%d",&num);
17        printf("Binary Equivalent is : ");
18        DecToBin(num);
19
20        return 0;
21
22}/*End of main()*/
23
24void DecToBin(int num)
25{
26        int stack[MAX], top=-1, rem;
27        while(num!=0)
28        {
29                rem = num%2;
30                push(rem, &top, stack);
31                num/=2;
32        }
33        while(top!=-1)
34                printf("%d", pop(&top, stack));
35        printf("\n");
36}
37
38
39void push(int x, int *top, int stack_arr[])
40{
41        if(*top == (MAX-1))
42                printf("Stack Overflow\n");
43        else
44        {
45                *top=*top+1;
46                stack_arr[*top] = x;
47        }
48}/*End of push()*/
49
50int pop(int *top, int stack_arr[])
51{
52        int x;
53        if(*top == -1)
54        {
55                printf("Stack Underflow\n");
56                exit(1);
57        }
58        else
59        {
60                x = stack_arr[*top];
61                *top=*top-1;
62        }
63        return x;
64}/*End of pop()*/