Skip to main content

Converts Infix expression into Postfix form

import java.io.*;
class Stac 
{ 
 char st_arr[]=new char[100];
 int t=-1;
 char top()
 {
  return(st_arr[t]);
 }
 void push(char ele)
 {
  if(t==99)
  {
  System.out.println("STACK is Full.\n");
  return;
  }
  st_arr[++t]=ele;
 }
 char pop()
 {
  if(t==-1)
  {
   return '#';
  }
  return(st_arr[t--]);
 }
 void display()
 {
  if(t==-1)
   System.out.println("Stack is empty\n");
  else
  {
   System.out.println("\tElements present in the stack are:");
   for(int k=0;k<=t;k++)
   System.out.print("\t"+st_arr[k]);
   System.out.println();
  }
 }
}
class In_post 
{
 char infix[]=new char[25];
 char postfix[];
 int prec(char c)
 {
  int p=0;
  switch(c)
  {
   case '(': p=0;
       break;
   case '+':
   case '-':
      p=1;
      break;
   case '*':
   case '/':
   case '%':
      p=2;
            break;
   default:p=-1;
  }
  return p;
 }
 void convert(String st)
 {
  infix=st.toCharArray();
  Stac s=new Stac();
  s.push('(');
  int i=infix.length;
  postfix=new char[i+2];
  char sym;
  int k=0;
  for(int j=0;j<infix.length;j++)
  {
   sym=infix[j];
   switch(sym)
   {
    case '(':s.push(sym);
       break;
    case ')':while(s.top()!='(')
       postfix[k++]=s.pop();
       s.pop();
       break;
    case '+':
    case '-':
    case '*':
    case '/':
    case '%':
       while(prec(s.top())>=prec(sym))
        postfix[k++]=s.pop();
       s.push(sym);
       break;
    default:postfix[k++]=sym;
   }
  }
  char ch;
  while((ch=s.pop())!='#')
  {
   postfix[k++]=ch;
  }
 }
 void show()
 {
  for(int i=0;i<postfix.length;i++)
   System.out.print(postfix[i]);
 }
}
class Inmain1
{
 public static void main(String args[]) throws IOException
 {
  BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
  System.out.println("enter an expression in infix form");
  String st=b.readLine();
  In_post a=new In_post();
  a.convert(st);
  System.out.println("The postfix form of the given expression is");
  a.show();
 }
}

Comments

Popular posts from this blog

Find Value of S=ut+1/2*a*t**2.

PROCEDURE:-        1.enter values for u,a,t to find distance        2.find distance with the formulae ut+1/2at 2        3.print the above result CODE:- #include<stdio.h> #include<conio.h> void main() {   float u,t,a,S;   clrscr();   printf(“enter values u,t,a”);   scanf(“%f %f %f”, &u,&t,&a);   S=(u*t)+(0.5*a*t*t);   printf(“\n  S = %f”, S); } Input:- enter values u,t,a               U=10,t=4,a=4.9 Output:- S =79.200