I'm trying a C programming code which will convert a decimal number into binary number and the binary values will be stored in a stack
According to my code, when running it shows some error responses. When trying to display the binary number using peek method, the application runs without an end.
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef enum{FALSE, TRUE} boolean;
typedef struct stack{
int top;
int a[MAX];
} stack;
void CreateStack(stack *s){
s->top = -1;
}
boolean isEmpty(stack *s){
return (s->top == -1);
}
boolean isFull(stack *s){
return(s->top == MAX - 1);
}
void push(stack *s, int data){
if(isFull(s)){
exit(1);
}
else{
s->top = s->top + 1;
s->a[s->top] = data;
}
}
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
return s->a[s->top];
s->top = s->top - 1;
}
}
int peek(stack *s){
return s->a[s->top];
}
void binary(stack *s, int num){
int n;
while(num != 0){
if(!isFull(s)){
n = num % 2;
push(s,n);
num = num / 2;
}
else{
exit(1);
}
}
}
void main() {
stack s;
CreateStack(&s);
int num,n;
printf("Enter the decimal number: ");
scanf("%d",&num);
binary(&s,num);
printf("Top = %d\n",peek(&s));
while(!isEmpty(&s)){
printf("%d ",pop(&s));
}
}
pop()
contains dead code — it returns value but top
decrement placed after the return operator and will be newer reached.
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
return s->a[s->top];
s->top = s->top - 1; // <------------
}
}
Change it in following manner:
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
int temp = s->a[s->top];
s->top = s->top - 1;
return temp;
}
}
p.s. As for me, else
keyword can be omitted here but it is taste issue:
int pop(stack *s) {
int temp;
if(isEmpty(s))
exit(1);
temp = s->a[s->top];
s->top = s->top - 1;
return temp;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments