POSTFIX EXPRESSION EVALUATION

JAVA PROGRAM TO EVALUATE A POSTFIX EXPRESSION USING STACK.


COMPUTER GENERATED OUTPUT IS:











CODING:


import java.io.*;
class postfix
{ int A[];int top,size;
postfix(int n)
{top=-1;A=new int[n];size=n;
}
void push(int ch)
{ if(top==size-1)
System.out.println("Overflow");
else
{top++;A[top]=ch;
}
}

int pop()
{ if(top==-1)
return(-99999);int ch=A[top];
if(top==size-1)
top=-1;
else
top--;
return(ch);
}

public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the post fix expression");
String s=br.readLine();postfix ob=new postfix(s.length());
System.out.println("Enter values Of\t:");
for(int i=0;i<s.length();i++)
{ char ch=s.charAt(i);
if(ch!='*'&&ch!='^'&&ch!='+'&&ch!='-'&&ch!='/')
{System.out.print("\n\t\t"+ch+"\t=\t");
ob.push(Integer.parseInt(br.readLine()));
}
else
{int ans=0; int a=ob.pop(),b=ob.pop();
if(a==-99999||b==-99999)
{System.out.println("Invalid postfix expression");
System.exit(0);
}
if(ch=='+')
ans=a+b;
if(ch=='-')
ans=b-a;
if(ch=='/')
ans=b/a;
if(ch=='*')
ans=b*a;
if(ch=='^')
ans=(int)Math.pow(b,a);
ob.push(ans);
}
}
int ans=ob.pop(); if(ob.pop()==-99999) System.out.println("\t\tAnswer\t=\t"+ans); else System.out.println("\t\tINVALID POSTFIX EXPRESSION"); }
}
}






Comments

Popular Posts