Question

In: Computer Science

In this project you will be writing a C++ program that uses a stack to convert...

In this project you will be writing a C++ program that uses a stack to convert an evaluate infix expression. Compilers often use this type of parsing. Note that the infix expression might not be syntactically correct.

Before evaluating an infix expression, you need to check if its balanced, then convert it to a postfix expression then finally evaluate the postfix.

You need to implement three methods:

1. public static Boolean checkBalance(String infixExpression)
2. public static String convertToPostfix(String infixExpression) 3. public static Double evaluatePostfix(String postFix)

Refer to your text book and class notes for the corresponding algorithms to implement these methods.

You need to use your own Stack implemented using Linked structure not C++ STL Stack. Your program should prompt the user for an expression, detect how many variables are there in the expression and prompt the user for their values.

Sample infix/Postfix Conversion

Infix Expression

Postfix Expression

a+b

a b+

a + b*c

a bc *+

a *b^ c

a bc ^ *

a + b*c ^ d

a bc d^ *+

( a + b ) *c

a b+ c *

(a +b ) * c

a b+ c *

( a + b ) / (c – d )

a b+ c d - /

( a + b * c^ d )^ ( e *f – g ^ h )

a b c d ^ * +e f * g h^ - ^

( a +b * c^ d ) ^( e* f– g h)

None. Invalid syntax. (What’s missing?)

a / b * c / d + ( e*f / g ^ h ) * (i – j)

a b / c * d / e f * g h^ / i j - * +

Sample input/output:

Enter your infix expression:
a+b*c
Your expression has 3 variables, please enter the value of variable 1: 3
please enter the value of variable 2:
6
please enter the value of variable 3:
28
Your equivalent postfix is:

abc*+
The evaluation is = 171.00

PLEASE ANSWER THE FOLLOWING IN C++!! I DON'T UNDERSTAND THE PROBLEM AT HANDS!! I WILL UPVOTE FOR WHOEVER ANSWERS IT CORRECTLY!! READ THE PROBLEM CAREFULLY!!!

Solutions

Expert Solution

PLEASE GIVE IT A THUMBS UP

#include<iostream>
#include <math.h>
#include <string.h>
#include<bits/stdc++.h>
#include<ctype.h> //for isdigit function
using namespace std;
int stackk[100];
int top=-1;
int value=0; //Global Declarations
int pop()
{

return (stackk[top--]);
}
void push(int x)
{
if(value==1)
{
int y;
y=pop();
stackk[++top]=x+10*y; //for more than one digit
}
else if(value==0)
{
stackk[++top]=x;
value=1;
}
}

void evaluate(char postfix[]){
char c;
int i=0,y,x;
while((c=postfix[i++])!='\0')
{
if(isdigit(c))
push(c-'0'); //for converting datatype
else if(c==',')
{
value=0;
}
else
{
x=pop(); //top element
y=pop(); //next top element
switch(c)
{
case'+':
push(x+y);
break;
case '-':
push(y-x);
break;
case '*':
push(y*x);
break;
case '/':
push(y/x);
break;
case '^':
push(pow(y,x));
break;
default:
cout<<"\nInvalid Operator";
}
}
}
cout<<"\n\nResult Of Evaluation:"<<stackk[top];
}

int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}

string infixToPostfix(string s)
{
std::stack<char> st;
st.push('N');
int l = s.length();
string ns;
for(int i = 0; i < l; i++)
{
if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
ns+=s[i];
else if(s[i] == '(')
st.push('(');   
else if(s[i] == ')')
{
while(st.top() != 'N' && st.top() != '(')
{
char c = st.top();
st.pop();
ns += c;
}
if(st.top() == '(')
{
char c = st.top();
st.pop();
}
}   
else{
while(st.top() != 'N' && prec(s[i]) <= prec(st.top()))
{
char c = st.top();
st.pop();
ns += c;
}
st.push(s[i]);
}

}
while(st.top() != 'N')
{
char c = st.top();
st.pop();
ns += c;
}

return ns;

}

bool checkbalance(string s){
for(int i=0;i<s.length()-1;i++){
if((s[i]>='a' && s[i]<='z') && (s[i+1]>='a' && s[i+1]<='z'))
return false;
}
return true;
}

int main()
{
string exp;
cin>>exp;
if(checkbalance(exp)==0){
cout<<"Not balance"<<endl;
return 0;
}
else{
string s=infixToPostfix(exp);
int n = s.length();
int c_n=0;
for(int i=0;i<n;i++){
if(s[i]>='a' && s[i]<='z')
c_n++;
}
cout<<"Your expression has "<<c_n<<" variables"<<endl;
char c[100];
int c_i=0;
c_n=1;
for(int i=0;i<n;i++){
string v;
if(s[i]>='a' && s[i]<='z'){
cout<<"Enter the value of variable "<<c_n<<": ";
cin>>v;
for(int k=0;v[k]!='\0';k++){
c[c_i]=v[k];
c_i++;
}
c_n++;
}
else{
c[c_i]=(char)s[i];
c_i++;
}
c[c_i]=',';
c_i++;
}
c[c_i-1]='\0';
evaluate(c);
}
}


Related Solutions

C++ code Inventory Item Stack You are writing an Inventory program that will allow the user...
C++ code Inventory Item Stack You are writing an Inventory program that will allow the user to enter a part into the inventory, take a part from the inventory, or quit. You are provided with the InvItem class (InvItem.h) and a partial Driver.cpp. You will be creating a DynamicStack class that should implement a Stack data structure. The DynamicClass should be implemented as a template class to allow any data type be added/removed from the stack. You will submit three...
Using the Stack ADT: Create a program that uses a stack. Your program should ask the...
Using the Stack ADT: Create a program that uses a stack. Your program should ask the user to input a few lines of text and then outputs strings in reverse order of entry. (Optional) Create a similar program that uses a stack. Your new program should ask the user to input a line of text and then it should print out the line of text in reverse. To do this your application should use a stack of Character. In Java...
2. Using the Stack ADT: Create a program that uses a stack. Your program should ask...
2. Using the Stack ADT: Create a program that uses a stack. Your program should ask the user to input a few lines of text and then outputs strings in reverse order of entry. In Java please.
in C++ For this program, you are going to implement a stack using an array and...
in C++ For this program, you are going to implement a stack using an array and dynamic memory allocation. A stack is a special type of data structure that takes in values (in our case integers) one at a time and processes them in a special order. Specifically, a stack is what's called a first-in-last-out (FILO) data structure. That is to say, the first integer inserted into the stack is the last value to be processed. The last value in...
How would you go about writing a MATLAB program to convert a phrase in Pig Latin...
How would you go about writing a MATLAB program to convert a phrase in Pig Latin to English. I have already written a script that converts phrases from English into Pig Latin; however, I am not sure how to reverse the process. Can anyone who know's MATLAB please help me out, thank you? P.S. I know that this is an unambigious task so it doesn't have to work completely well. With the most minor assumptions made, if it could covert...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else...
C# To write a program using a stack and a program using a queue. Code a...
C# To write a program using a stack and a program using a queue. Code a class encapsulating a queue of foods using a circular array. A food has the following attributes: name, the number of calories per serving and the number of servings per container. Limit your queue to 20 food items. In addition to writing the enqueue, dequeue, and peek methods, you will write two more methods: a method that returns the average calories per serving of all...
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
You will be writing a C program to test the data sharing ability of a thread...
You will be writing a C program to test the data sharing ability of a thread and process. Your C program will do the following: 1. Your parent program will have three variables: int x,y,z; which to be initialized as 10, 20, and 0, respectively. 2. parent creating child: parent will create a child by fork() and the child will perform z = x+y (i.e., add x and y and store the results in z). parent will wait for child...
Convert the C program shown below to MIPS program. You may choose the $t registers, but...
Convert the C program shown below to MIPS program. You may choose the $t registers, but must correctly apply the $a and $v registers used in function calls. Please do not include an exit syscall in your MIPS solution. Hint: review jr and jal instructions. int fun( int a, int b ) { if ( a >= b ) return b + 2*a; else return b + a; } void main() { } int a = 10; int b =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT