Question

Total point: 15 Introduction: For this assignment you have to write a c program that will...

Total point: 15

Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result.

What should you submit?

Write all the code in a single file and upload the .c file.

Problem

We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In computer’s language however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix.

Write a program that takes an “infix” expression as input, uses stacks to convert it into postfix expression, and finally evaluates it. It must support the following operations:

+ - / * ^ % (

Example

Infix expression:

(7 – 3) / (2 + 2)

Postfix expression:

7 3 - 2 2 + /

Result: 1

Rubric:

  1. If code does not compile: 0
  1. Checking the balance of the parenthesis: 2 point
  1. Incorrect postfix expression per test case: -2 points
  1. Correct postfix but incorrect value per test case: -1 points
  1. Handling single digit inputs: maximum 13 point
  1. Handling two-digit inputs: 100 percent (if pass all test cases)

Some hints (but it is not the only way):

  1. You will need to use stacks in three places
  1. One for parenthesis check [char stack]
  2. One during infix to postfix [char stack]
  1. One during evaluation [int stack]

For a and b above, you can use same array and same push, pop method as both of them are char. But for evaluation you have int stack and you might consider to create another push pop method to handle it. Maybe push_int, pop_int, etc.

  1. You can create a function for obtaining operator priority. It should take an operator as input and return its precedence as an integer.
  1. During evaluation you will need to convert char into integer. Example for single digit: char c = '5';

int x = c - '0';

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program Screenshot:

Sample output:

Code to copy:

#include <stdio.h>
#include <ctype.h>
//define the size of the stack as 50
#define SIZE 50
//declare a character array
//and assign the top value with -1 globally.
char stack[SIZE];
int top = -1;

//definition of the function
//it removes the space in the given string
void removeSpaces(char* data)
{
   //define char pointers
   char* temp1 = data;
   char* temp2 = data;
   //iterate the loop and remove the spaces
   while (*temp2 != 0)
   {
       *temp1 = *temp2++;
       if (*temp1 != ' ')
           temp1++;
   }
   *temp1 = 0;
}

//definition of the function push()
void push(char item)
{
   //increment the top values
   //and store the item in the stack
   stack[++top] = item;
}

//definition of the function pop()
char pop()
{
   //decrement the get value of
   //stack at top and decrement the top value
   return (stack[top--]);
}

//definition of the function getPrecedence()
//takes a character and return its precedence values
int getPrecedence(char ch)
{
   switch (ch)
   {
   case '#':
       return 0;
   case '(':
       return 1;
   case '+':
   case '-':
       return 2;
   case '*':
   case '/':
       return 3;
   }
}

//definition of the function convertToPostfix()
//convert the infix string to postfix string
void convertToPostfix(char *infix, char *postfix)
{
   //declare the variables
   char ch, item;
   int i = 0, j = 0;
   //call the function to remove
   //the space in the infix string
   removeSpaces(infix);
   // call push() to insert '#' into the stack
   push('#');
   //iterate the each character of the infix string.
   while ((ch = infix[i++]) != '\n')
   {
       //if the character is open brace
       //push the character into the stack
       if (ch == '(')
       {
           push(ch);
       }
       //if the character is alphanumeric
       else if (isalnum(ch))
       {
           //assign the character to postfix string
           postfix[j] = ch;
           j++;
           postfix[j] = ' ';
           j++;
       }
       //if the character is closed brace
       //pop the character from the stack
       //assign the character to postfix string
       //until open brace occur
       else if (ch == ')')
       {
           while (stack[top] != '(')
           {
               postfix[j] = pop();
               j++;
               postfix[j] = ' ';
               j++;
           }  
           //pop the value from the stack
           item = pop();
       }
       else
       {
           //call getPrecedence() and check the precedence
           //of ch and the top value of stack
           while (getPrecedence(stack[top]) >= getPrecedence(ch))
           {
               //pop the character from the stack
               //assign the character to postfix string
               postfix[j] = pop();
               j++;
               postfix[j] = ' ';
               j++;
           }
           //push the character into the stack
           push(ch);
       }
   }
   //pop the character from the stack and push into
   //the postfix until end of the stack.
   while (stack[top] != '#')
   {
       postfix[j] = pop();
       j++;
       postfix[j] =' ';
       j++;
      
   }
   postfix[j] = 0;
}

//definition of the function evaluatePostfix
//evaluates and returns the value of postfix.
int evaluatePostfix(char *postfix)
{
   //declare the variables.
   int i = 0, value1, value2;
   char ch;

   while ((ch = postfix[i++]) != 0)
   {
       if (ch != ' ')
       {
           //if the character is digit,
           //convert into character and push into stack
           if (isdigit(ch))
           {
               push(ch - '0');
           }
           else
           {
               //pop two values from the stack
               value2 = pop();
               value1 = pop();
               //depends on the character,
               //find the result of the opration.
               //and push into the stack.
               switch (ch)
               {
               case '+': push(value1 + value2);
                   break;
               case '-': push(value1 - value2);
                   break;
               case '*': push(value1*value2);
                   break;
               case '/': push(value1 / value2);
                   break;
               case ' ':
                   break;
               }
           }
       }
      
   }
   //return the top value of the stack.
   return stack[top];
}
int main()
{
   //declare the variables
   char infix[50], postfix[50];
   //prompt and read the infix expression
   printf("Infix expression: ");
   fgets(infix, 50, stdin);
   //convert into postfix
   convertToPostfix(infix, postfix);
   //print the postfix expression
   printf("\nPostfix Expression: %s", postfix);
   //make top as -1.
   top = -1;
   //print the result.
   printf("\n\nResult of evaluation of postfix expression: %d\n", evaluatePostfix(postfix));
   return 0;
}

Add a comment
Know the answer?
Add Answer to:
Total point: 15 Introduction: For this assignment you have to write a c program that will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • i want similar for this code to solve two questions : 1- Write a program to...

    i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c;...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • Code should be written in java Write a program to convert an infix expression to postfix...

    Code should be written in java Write a program to convert an infix expression to postfix expression using stack. Algorithm: a) Create a stack b) For each character t in the input stream If(t is an operand) append t to the output. Else if (t is a right parenthesis) Pop and append to the output until a left parenthesis is popped (but do not append this parenthesis to the output). Else if(t is an operator or left parenthesis) Pop and...

  • In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack...

    In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack are of generic DataType. This means use should use templating and your Node class. Structure  The stack data items are linearly ordered from the most recently added (the top) to the least recently added (the bottom). This is a LIFO scheme. Data items are inserted onto (pushed) and removed from (popped) the top of the stack.  Operations  Constructor. Creates an empty stack.  Copy constructor....

  • EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation;...

    EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation; in it, operators are written between their operands: X + Y. Such expressions can be ambiguous; do we add or multiply first in the expression 5 + 3 * 2? Parentheses and rules of precedence and association clarify such ambiguities: multiplication and division take precedence over addition and subtraction, and operators associate from left to right. This project implements and exercises a stack-based algorithm that evaluates...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT