Write a program which converts infix expression entered by the user into postfix expression.
Requirements:
Implement this using arrays
Make functions
No global decelerations
Run test in main
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <ctype.h>
void push(char elem , char *array , int & top)
{
array[++top] = elem;
}
char pop( char* array, int& top)
{
return(array[top--]);
}
int pr(char symbol)
{
if (symbol == '^')/* exponent operator, highest precedence*/
{
return(3);
}
else if (symbol == '*' || symbol == '/')
{
return(2);
}
else if (symbol == '+' || symbol == '-') /* lowest precedence */
{
return(1);
}
else
{
return(0);
}
}
/* Main Program */
int main()
{
const int SIZE = 100;
char array[SIZE];
int top = -1;
char infix[50], postfix[50], ch, elem;
int i = 0, k = 0;
printf("Enter Infix Expression : ");
scanf("%s", infix);
push('#' , array , top);
while ((ch = infix[i++]) != '\0')
{
if (ch == '(') push(ch , array , top);
else
if (isalnum(ch)) postfix[k++] = ch;
else
if (ch == ')')
{
while (array[top] != '(')
postfix[k++] = pop(array , top);
elem = pop(array , top); /* Remove ( */
}
else
{ /* Operator */
while (pr(array[top]) >= pr(ch))
postfix[k++] = pop(array , top);
push(ch , array , top);
}
}
while (array[top] != '#') /* Pop from array till empty */
postfix[k++] = pop(array , top);
postfix[k] = '\0'; /* Make postfix as valid string */
printf("\nPostfix Expression = %s\n", postfix);
system("pause");
return 0;
}
Comments
Leave a comment