0% found this document useful (0 votes)
5 views3 pages

Inftopost Programc

The document contains a C++ program that converts infix expressions to postfix notation using a stack data structure. It defines a function to determine operator precedence and processes each character of the infix expression accordingly. The main function prompts the user for an infix expression and outputs the corresponding postfix expression.

Uploaded by

kkr795707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Inftopost Programc

The document contains a C++ program that converts infix expressions to postfix notation using a stack data structure. It defines a function to determine operator precedence and processes each character of the infix expression accordingly. The main function prompts the user for an infix expression and outputs the corresponding postfix expression.

Uploaded by

kkr795707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

#include <stack>
#include <string>
using namespace std;

// Function to return precedence of operators


int precedence(char op) {
if (op == '^') return 3;
else if (op == '*' || op == '/') return 2;
else if (op == '+' || op == '-') return 1;
else return -1; // For parentheses
}

// Function to convert infix expression to postfix


string infixToPostfix(string infix) {
stack<char> st; // Stack to hold operators
string postfix = ""; // Output postfix expression

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


char ch = infix[i];

// If the character is an operand, add it to the output


if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9')) { postfix += ch; }
// If the character is '(', push it onto the stack
else if (ch == '(') {
st.push(ch);
}
// If the character is ')', pop and add to output
// until '(' is encountered
else if (ch == ')') {
while (!st.empty() && st.top() != '(') {
postfix += st.top();
st.pop();
}
st.pop(); // Pop '(' from the stack
}
// If the character is an operator
else {
while (!st.empty() && precedence(st.top()) >= precedence(ch)) {
postfix += st.top();
st.pop();
}
st.push(ch); // Push the current operator onto the stack
}
}

// Pop all remaining operators from the stack


while (!st.empty()) {
postfix += st.top();
st.pop();
}

return postfix;
}

int main() {
string infix;
cout << "Enter an infix expression: ";
cin >> infix;

string postfix = infixToPostfix(infix);


cout << "Postfix expression: " << postfix << endl;

return 0;
}

You might also like