Tuesday, April 3, 2012

Program to convert decimal number to Hexadecimal,Octal or Binary using Stack


/************<soeasyprograms.blogspot.in>***************/
#include<stdio.h>
#include<conio.h>


struct node{
int info;
struct node *link;
} *top=NULL;




void push(int a)
{
struct node *tmp;
tmp = (struct node *)malloc(sizeof(struct node));
tmp->info=a;
tmp->link=top;
top=tmp;
}/*End of push()*/


void pop()
{
struct node *tmp;
if(top == NULL)
printf("Stack is empty\n");
else
{ tmp=top;
printf(" %d",tmp->info);
top=top->link;
free(tmp);
}
}


void popc()
{
struct node *tmp;
if(top == NULL)
printf("Stack is empty\n");
else
{ tmp=top;
printf(" %c",tmp->info);
top=top->link;
free(tmp);
}
}


void hexa(int n)
{
int a,i=1;
while(n>0)
{
a=n%16;
n=n/16;
if(a>9)
push(a-10+'A');
else
push(a+'0');
}
printf("output is:");
while(i<=top)
{
popc();
i++;
}


}


void octal(int n)
{
int a,i=1;
while(n>0)
{
a=n%8;
n=n/8;
push(a);
}
printf("\n octal equivalent of given number is");


while(i<=top)
{
pop();
i++;
}
}


void binary(int n)
{
int a,i=1;
while(n>0)
{
a=n%2;
n=n/2;
push(a);
}
printf("\nBinary equivalent of given number is");
       while(i<=top)
{
pop();
}


}




main()
{
int n,item;
clrscr();
printf("1. Hexaconversion\n");
printf("2. Octal conversion\n");
printf("3. Binary conversion\n");
printf("4. Exit\n");
printf("Enter any choice\n");
scanf(" %d",&n);
printf("Enter element");
scanf(" %d",&item);
switch(n)
{
case 1:
hexa(item);
break;


case 2:
octal(item);
break;


case 3:
binary(item);
break;


case 4:


break;
default:
break;
}
getch();
}
/************<soeasyprograms.blogspot.in>***************/


Output of this program is:



1 comment:

  1. why this program has error ??
    please e-mail me the answer at nini.amalina@yahoo.com

    ReplyDelete