Write a C Program to convert decimal to binary using stack

By | April 12, 2017

Convert decimal to binary using stack


Write a C Program to convert decimal to binary using stack . Here’s simple Program to convert decimal to binary using stack in C Programming Language.


What is Stack ?


Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of objects.


Basic Operations : :


  • push() − Pushing (storing) an element on the stack.
  • pop() − Removing (accessing) an element from the stack.
  • peek() − get the top data element of the stack, without removing it.
  • isFull() − check if stack is full.
  • isEmpty() − check if stack is empty.

Below is the source code for C Program to convert decimal to binary using stack which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/*  C Program to convert decimal to binary using stack  */

#include<stdio.h>
#include<stdlib.h>
#define MAX 50

int isEmpty(int top, int stack_arr[]);
void push(int x, int *top, int stack_arr[]);
int pop(int *top, int stack_arr[]);
void DecToBin(int num);

int main()
{
	int num;
	printf("Enter an integer : ");
	scanf("%d",&num);
	printf("Binary Equivalent is : ");
	DecToBin(num);

	return 0;

}/*End of main()*/

void DecToBin(int num)
{
	int stack[MAX], top=-1, rem;
	while(num!=0)
	{
		rem = num%2;
		push(rem, &top, stack);
		num/=2;
	}
	while(top!=-1)
		printf("%d", pop(&top, stack));
	printf("\n");
}


void push(int x, int *top, int stack_arr[])
{
	if(*top == (MAX-1))
		printf("Stack Overflow\n");
	else
	{
		*top=*top+1;
		stack_arr[*top] = x;
	}
}/*End of push()*/

int pop(int *top, int stack_arr[])
{
	int x;
	if(*top == -1)
	{
		printf("Stack Underflow\n");
		exit(1);
	}
	else
	{
		x = stack_arr[*top];
		*top=*top-1;
	}
	return x;
}/*End of pop()*/

OUTPUT : :


/*  C Program to convert decimal to binary using stack  */

Enter an integer : 89
Binary Equivalent is : 1011001

Process returned 0

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post….

Leave a Reply