Skip to main content

Binary to Decimal using Stack in C

CODE

 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
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
int STACK[SIZE],TOP=-1;
int power(int i)
{
    int res=1;
    while(i--)
    {
        res=res*2;
        
    }
    
    return res;
}
void push(int n)
{
 if (TOP==SIZE) 
 printf("OVerflow");
 else
 STACK[++TOP]=n;
}
int pop()
{
 if (TOP==-1) return -1;
 else
  return STACK[TOP--];
}
void main()
{
 int num,i=0,arr[SIZE],j,res=0,temp;
 printf("Enter the number");
 scanf("%d",&num);
printf("\nEntered number=%d\n",num);
 while(num)
 {
 arr[i++]=num%10;
 num/=10;
 }

 for(j=i-1;j>=0;j--)
 push(arr[j]);


 for(j=0;j<i;j++)
 {
 res=res+(pop()*power(j));
 }

 printf("\nResult=%d",res);
 getchar();
}


Comments