0% found this document useful (0 votes)
2 views

ass2

This document contains a C++ program that converts infix expressions to postfix and prefix notations. It includes functions to determine operator precedence and associativity, as well as to handle the conversion process using a stack. The main function allows user interaction to choose the type of conversion or to exit the program.

Uploaded by

Anirudh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ass2

This document contains a C++ program that converts infix expressions to postfix and prefix notations. It includes functions to determine operator precedence and associativity, as well as to handle the conversion process using a stack. The main function allows user interaction to choose the type of conversion or to exit the program.

Uploaded by

Anirudh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

#include <bits/stdc++.

h>

using namespace std;

int prec(char c) {

if (c == '^')

return 3;

else if (c == '/' || c == '*')

return 2;

else if (c == '+' || c == '-')

return 1;

else

return -1;

char associativity(char c) {

if (c == '^')

return 'R';

return 'L';

string infixToPostfix(string s) {

stack<char> st;

string result;

for (int i = 0; i < s.length(); i++) {

char c = s[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c
<= '9'))

result += c;

else if (c == '(')

st.push('(');

else if (c == ')') {

while (st.top() != '(') {

result += st.top();

st.pop();

st.pop();

else {

while (!st.empty() && prec(s[i]) <= prec(st.top()) &&

associativity(s[i]) == 'L') {

result += st.top();

st.pop();

st.push(c);

}
while (!st.empty()) {

result += st.top();

st.pop();

return result;

string infixToPrefix(string s) {

reverse(s.begin(), s.end());

for (int i = 0; i < s.size(); i++) {

if (s[i] == '(')

s[i] = ')';

else if (s[i] == ')')

s[i] = '(';

string postfix = infixToPostfix(s);

reverse(postfix.begin(), postfix.end());

return postfix;

}
void print(string s1) {

for (int i=0; i<s1.size(); i++) {

cout<<s1[i];

cout<<endl;

int main() {

string exp;

cout<<"Enter the infix Expression:"<<endl;

cin>>exp;

bool ans=true;

int choice;

while(ans) {

cout<<"Press '1' to Convert infix to postfix"<<endl;

cout<<"Press '2' to convert infix to prefix"<<endl;

cout<<"Press '3' to Exit"<<endl;

cout<<"Enter the choice-->"<<endl;

cin>>choice;

switch(choice) {

case 1:
print(infixToPostfix(exp));

break;

case 2:

print(infixToPrefix(exp));

break;

case 3:

cout<<"Exited Successfully"<<endl;

ans=false;

break;

return 0;

You might also like