Tuesday 31 January 2017

Infix to Postfix Conversion using stacks using Array. ONLY FOR EXPRESSIONS WITHOUT BRACKETS : C program

#include<stdio.h>
#define MAX 50
char stack[MAX];
int top=-1;

int preced(char ch)
{
 switch(ch)
 {
  case '+':
  case '-':
     return 1;
     break;
  case '*': 
  case '/':
     return 2;
     break;
  case '#':
     return 0;
     break;
  default:
     return 3;
 }
}

void push(char item)
{
 if(top == MAX-1)
 {
  printf("stack is full");
  return;
 }
 top=top+1;
 stack[top]=item;
}

void pop()
{
 if(top == -1)
 {
  printf("stack empty");
  return;
 }
 printf("%c",stack[top]);
 top=top-1;
}
main()
{
char ch;
push('#');
printf("enter the given infix expression\n At the end type #");
fflush(stdin);
scanf("%c",&ch);
while(ch != '#')
{
 while(preced(stack[top])>=preced(ch))
 {
  pop();
 }
 push(ch);
 scanf("%c",&ch);
}
while(stack[top]!= '#')
 pop();
}


No comments:

Post a Comment