Search
 
SCRIPT & CODE EXAMPLE
 

CPP

prefix using stack

#include<iostream>
#include<stack>
using namespace std;

int EvaluatePrefix(string exp);
bool IsNumber(char ch);
bool IsOperator(char ch);
int PerformOperation(char ch, int op1, int op2);

int main()
{
	cout << "Prefix form: <operator> <operand> <operand>." << endl;
	string exp;
	cout << "
Enter Prefix Expression: ";
	cin >> exp;
	int result = EvaluatePrefix(exp);
	cout << "
Result = " << result << endl;

	return 0;
}
//
int EvaluatePrefix(string exp)
{
	stack<char> s;
	for (int i = exp.length(); i >= 0; i--)
	{
		if (IsNumber(exp[i]))
		{
			s.push(exp[i]-'0');
		}
		else if (IsOperator(exp[i]))
		{
			int op1 = s.top();    s.pop();
			int op2 = s.top();    s.pop();
			int result = PerformOperation(exp[i],op1,op2);
			s.push(result);
		}
	}
	return s.top();
}
//
bool IsNumber(char ch)
{
	if (ch >= '0' && ch <= '9')
		return true;
	return false;
}
//
bool IsOperator(char ch)
{
	if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
		return true;
	return false;
}
//
int PerformOperation(char ch, int op1, int op2)
{
	if (ch == '+')             return op1 + op2;
	else if (ch == '-')        return op1 - op2;
	else if (ch == '*')        return op1 * op2;
	else if (ch == '/')        return op1 / op2;
	else                       return -1;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: Restart the computer in c++ after the default time (30) seconds. (Windows) 
Cpp :: Write a C++ program to Computing Mean and Median Using Arrays 
Cpp :: pointers in cpp 
Cpp :: end vs cend in cpp 
Cpp :: surf interpolation matlab 
Cpp :: code runner c++ syntax error 
Cpp :: check if a string is a prefix of another c++ 
Cpp :: return multiple values c++ 
Cpp :: how does sorting array works in c++ 
Cpp :: sort array in descending order c++ 
Cpp :: what is c++ 
Cpp :: nand in cpp 
Cpp :: input time from console C++ 
Cpp :: what does map.count() return in c++ 
Cpp :: Types of Conversions- C++ 
Cpp :: reverse a stack in c++ using another stack 
Cpp :: check whether kth bit is 1 
Cpp :: what do I return in int main() function c++ 
Cpp :: Nested ternary operator C++ 
Cpp :: Equalize problem codeforces 
Cpp :: fishes code in assignment expert 
Cpp :: beecrowd problem 1003 solution in c++ 
Cpp :: Runtime error(Exit status:153(File size limit exceeded)) c++ 
Cpp :: set keybinding for compiling c++ program in neovim 
Cpp :: print an array c++ 
Cpp :: find the mminimum of the vector and its position in c++ 
Cpp :: result += a +b in c++ meaning 
Cpp :: c++ FAILED: objekt aufruf : symbol(s) not found for architecture x86_64 
Cpp :: How to write string in lpcstr in c++ 
Cpp :: determining whether a array is a subsequence of another array 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =