-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecimal_to_binary.c
More file actions
68 lines (54 loc) · 1.07 KB
/
decimal_to_binary.c
File metadata and controls
68 lines (54 loc) · 1.07 KB
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
#include <stdio.h>
#include <stdlib.h>
#define N 32
struct stack {
int data[N];
int top;
};
void initStack(struct stack *s) {
s->top = -1;
}
int isEmpty(struct stack *s) {
return s->top == -1;
}
int isFull(struct stack *s) {
return s->top == N - 1;
}
void push(struct stack *s, int value) {
if (isFull(s)) {
printf("Stack Overflow \n");
exit(1);
}
s->data[++(s->top)] = value;
}
int pop(struct stack *s) {
if (isEmpty(s)) {
printf("Stack is empty \n");
exit(1);
}
return s->data[(s->top)--];
}
int decimalToBinary(int decimal) {
struct stack s;
initStack(&s);
if (decimal==0) {
printf("the binary equivalent is 0");
return 0;
}
while(decimal>0) {
push(&s, decimal % 2);
decimal = decimal / 2;
}
printf("Binary equivalent: ");
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
decimalToBinary(decimal);
return 0;
}