1 Replies - 542 Views - Last Post: 10 October 2012 - 02:11 PM Rate Topic: -----

#1 nawal_mirza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 10-October 12

prefix evaluation

Posted 10 October 2012 - 12:39 PM

i've done postfix evaluation using stack and now i am trying prefix,ireversed a string using stack and then tried to evaluate bt it doesn't :(
code doesn't give any error but i didn't get the desired output
here's the code

//Evaluating Postfix expression

#include <iostream>
#include <process.h>
#include <string>
#include <math.h>
using namespace std;
int calc (int op1, int op2, char ch);

template <class Type>
class Stack
{
private:
	Type *stack;
	int top;
	int Maxsize;
public:
	Stack(int Max)
	{
		stack = new Type[Max];
		top = -1;
		Maxsize = Max;
	}
	bool isempty()
	{
		return (top==-1);
	}
	bool isfull()
	{
		if (top == Maxsize)
			return true;
		else
			return false;
	}
	void push(Type val)
	{
		if (!isfull())
		{
			top++;
			stack[top] = val;
		}
		else
		{
			cout << "stack overflow";
			exit(1);
		}
	}

	Type pop()
	{
		if (!isempty())
		{
			int x = stack[top];
			top--;
			return x;
		}
		else
		{
			cout << "stack underflow";
			exit(1);
		}
	}

	Type stacktop()
	{
		if (!isempty())
			return stack[top];
		else
		{
			cout << "stack underflow";
			exit(1);
		}

	}


};
void main()
{
	Stack<int> s(4);
	string s1,exp;
	int op1, op2, r;
	cout << "Enter prefix exp";
	cin >>exp;
	for (int i=0; i< exp.length(); i++)
	{
		char symb= exp[i];
		s.push(symb);
	}
		for (int j=s.stacktop();!s.isempty(); j--)
	{
		
		s1=s.pop();
	}
	for (int k=0; k< s1.length(); k++)
	{
	    char symb= s1[i];
		
		if (symb >='0' && symb <= '9')
			s.push(symb - '0');
		else
		{
			op2 = s.pop();
			op1 = s.pop();
			r = calc(op1, op2, symb);
			s.push(r);
		}
	}
	cout << "Result is "<<  s.pop();	
}
int calc (int op1, int op2, char ch)
{
	switch (ch)
	{
	case '+': return op1+op2; break;
	case '-': return op1-op2; break;
	case '*': return op1*op2; break;
	case '/': return op1/op2; break;
	case '$': return pow(op1,op2); break;
	}
}

This post has been edited by Salem_c: 10 October 2012 - 01:01 PM
Reason for edit:: added [code][/code] tags - learn to use them yourself


Is This A Good Question/Topic? 0
  • +

Replies To: prefix evaluation

#2 jimblumberg  Icon User is online

  • member icon


Reputation: 4142
  • View blog
  • Posts: 12,892
  • Joined: 25-December 09

Re: prefix evaluation

Posted 10 October 2012 - 02:11 PM

What did you input to the program?

What output does the program produce?

What do you expect?

Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1