forked from tannuchoudhary/Data-structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decimal_binary_conversion.c
129 lines (103 loc) · 2.56 KB
/
decimal_binary_conversion.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*Conversion of decimal numbers into binary using stack*/
/*The concept is that we will divide the entered number by base number i.e 2 until we will
get zero and we will store all the remainders in stack until we will get remainder zero and then
we will print all the remainders by popping them out of stack*/
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int * item ;
int top;
int size;
}stack;
/*Function prototype*/
void push(stack *, int);
int pop(stack *);
void init(stack *, int);
void deallocate(stack *);
int isUnderflow(stack *); /*Just made shortcuts for underflow and overflow condition*/
int isOverflow(stack *);
/*Function definition*/
int isOverflow(stack *sp)
{
return sp->top == sp->size-1;
}
int isUnderflow(stack *sp)
{
return sp->top == -1;
}
void push(stack *sp, int value)
{
if(isOverflow(sp))
{
int * temp, i;
temp = (int *)malloc(sizeof(int) * sp->size * 2);
if(temp == NULL)
{
printf("Stack overflow\n");
return;
}
for(i=0; i<=sp->top; i++)
{
temp[i] = sp->item[i];
}
free (sp->item);
sp->item = temp;
sp->size *= 2;
}
sp->top++;
sp->item[sp->top] = value;
}
int pop(stack *sp)
{
if(isUnderflow(sp))
{
printf("Stack underflow\n");
return -9999;
}
int value;
value = sp->item[sp->top];
sp->top--;
return value;
}
void init(stack *sp, int size)
{
sp->top = -1;
sp->item = (int*)malloc(sizeof(int)*size);
if(sp->item == NULL)
{
printf("Memory cannot be allocated\n");
exit(1);
}
sp->size = size;
}
void deallocate(stack *sp)
{
if (sp->item != NULL)
{
free(sp->item);
}
}
int main()
{
int num, rem, new_num, temp;
const int BASE = 2;
stack s1;
init(&s1, 10);
printf("Enter any number :");
scanf("%d", &num);
temp = num;
while (num>0) /*Loop will run until we will get zero after dividing it by 2*/
{
rem = num % BASE; /*Remainder after dividing by 2 will be stored in rem var*/
push(&s1, rem); /*we will push the remainder into stack*/
num /= BASE; /*And the value of number will be changed into the number we will get after dividing it by 2*/
}
printf("Binary conversion of %d is ", temp);
while(!isUnderflow(&s1))
{
printf("%d",pop(&s1));
}
deallocate(&s1);
return 0;
}