0

Program to convert the given decimal number to binary number using stack in c.*

#include<stdio.h>
int binstack[10];
int top = -1;
int num;
int quo;
int rem;

void push(int x){
    top = top +1;
    binstack[top] = x;
}

void pop(){
    printf("%d",binstack[top]);
    top = top -1;
}

void peek(){
    printf("The top most element is %d",binstack[top]);
}

void binary(){
    printf("enter the number:");
    scanf("%d ",&num);
    while(num>1){       
        int rem = num%2;
        if(rem != 0){
            push(1);
        }
        else{
            push(0);
        }
        num = num/2;        
    }
    if(num<=1){
            push(1);
    }    
}

void main(){
    binary();
    while(top!=-1){
    pop();
   }

}

I tried to get the binary number as the output for the corresponding decimal input but what I got all is the stucking of my program. And it sometimes gives output only when I press the ctrl+c button to terminate the program.enter image description here

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
  • You should probably add a guard to `pop` so it doesn't access `binstack[-1]` or decrement `top` if it is already `-1`. You may have an endless loop under some conditions if top becomes -2 for instance but I wasn't able to duplicate it with a few different large and small values. Worth noting that entering 0 gives 1 as a result which is incorrect. Printing a `\n` after you finish printng all of the digits or `fflush(stdout);` may help if it is just a buffering issue. – Retired Ninja Nov 04 '22 at 07:16
  • 2
    Welcome to SO. Please do not post pictures of nearly empty windows. Your output is plain text. Please copy&paste it as formatted text in your question. – Gerhardh Nov 04 '22 at 09:32
  • Try calling fflush after your printf in the pop function. – danger Nov 04 '22 at 13:17

1 Answers1

1

Please remove the space in the scanf() function. you should write it like this scanf("%d",&num);.

For more details, check the previous What does space in scanf mean?.

Aatif Shaikh
  • 322
  • 2
  • 14