Problem Consider simple infix expressions that consist of single-digit operands;
ID: 3599930 • Letter: P
Question
Problem
Consider simple infix expressions that consist of single-digit operands; the operators +, -, *, and /; and the parentheses. Assume that unary operators are illegal and that the expression contains no embedded spaces. Design and implement a class of infix calculators. Use an algorithms to evaluate infix expressions as entered into the calculator. The calculator must first convert the infix expression to postfix form and then evaluates the resulting postfix expression. (The program to be written in C++).
Requirement
Use the link-based Stack with exceptions.
Write a main function to test your calculators.
Other Requirements
a) You should not assume that the expression is well-formed. The user is asked to reenter an expression if the expression entered is not well-formed.
b) You should not assume that the parentheses in the expression are balanced. The user is asked to reenter an expression if the expression entered is not balanced.
c) Your program should allow the user to evaluate additional expressions until the user wants to end the program.
Explanation / Answer
ANSWER::
#include<stdio.h>
char stack[20];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
}
main()
{
char exp[20];
char *e, x;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.