Tuesday, January 5, 2016

Solve the given equations using Stack(Post fix Notation)

9:05 PM

Steps:
1. Read the equation as a string.
2.first pop two operand from the equation
3.If the third character is an operator we do the calculate the value for that operator and the operands.
4.Then push the calculated value in to the stack.
5.finally print the final value.


Implementation
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author suthaas
*/
import java.util.*;
public class postfix_calculation
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the equation");
String ex=sc.next();
stack s1=new stack(ex.length());
char operator;
int ans,a,b;
for(int i=0;i<ex.length();i++)
{
operator=ex.charAt(i);
ans=Character.getNumericValue(operator);
switch( operator)
{
case '+': a=s1.pop();
b=s1.pop();
ans=a+b;break;
case '-': a=s1.pop();
b=s1.pop();
ans=a-b;break;
case '*': a=s1.pop();
b=s1.pop();
ans=a*b;break;
case '/': a=s1.pop();
b=s1.pop();
ans=a/b;break;
}
s1.push(ans);
}
System.out.println(s1.pop());
}
}
/**
*
* @author sutha
*/
public class stack
{
int size;
int[] array;
int top;
public stack(int s)
{
size=s;
top=0;
array=new int[s];
}
public void push(int elt)
{
top=top+1;
array[top]=elt;
}
public int pop()
{
int mypopped=array[top];
top=top-1;
return mypopped;
}
public boolean isEmpty()
{
return (top==0);
}
public boolean isFull()
{
return (top==size-1);
}
}
view raw stack.java hosted with ❤ by GitHub


Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 CSC. All rights resevered. Designed by Templateism

Back To Top