# Prefix to Infix Using Stack

Prefix to Infix Using Stack” is a classic example of  stack data structure. Stack can be used to convert given prefix expression to corresponding infix expression.

Operator: Operator are symbols that instruct the computer to perform simple and single tasks. Examples of operators includes + (Addition), – (Subtraction), * (multiplication),… and many more.

Operand: Operands are values or variable on which operator works its tasks. Examples of Operand includes “a”, “b”, 23, 12,.. and many more.

The Steps to convert Prefix to Infix Using Stack Expression are as follows:

1. Scan the Prefix Expression form right to left.
2. Initialize the string stack.
3. If the scanned character is operand, push it into stack.
4. Else if the scanned character is operator, pop two strings from the stack namely, temp1 and temp2, then push

(temp1 operator temp2) into stack.

1. Repeat steps from 3 to 4 until we scanned all the characters.
2. At the end, only infix string will be left into stack, pop and return it.

#### Example:

Suppose, we want to convert the following prefix expression to infix expression:

#### Algorithm for converting Prefix to Infix Using Stack

```Algo prefix_2_infix (postfix)
{    // input- valid prefix expression
//output- equivalent infix expression
1.    Createstack (stack).
2.    i=sizeof(prefix)-1.
3.    loop(i>=0)
{
a.if prefix[i] is an operator
{
Operand1=popstack().
Operand2=popstack().
temp= concatenate “(“+ operand1 + prefix[i] + operand2 + “)”.
pushstack (temp).
}
b.else if prefix[i] is an operand
Then push prefix[i] into stack.
c.    Decrement  i with 1.
}
4.    infix= popstack().
5.    Return infix.
}// END OF ALGO.

```

#### C++ Program for converting Prefix to Infix Using Stack is as follows:

```/* Program for converting Prefix to Infix Using Stack */
#include <iostream>
#include<string>
#define sizes 100
using namespace std;
class stack
{
string item[sizes];
int top;
public:
stack()
{
top=-1;
}
void push(string st)
{
if(top==sizes-1)
{
cout<<"stack overflow!!";
return;
}
top++;
item[top]=st;
}
string pop()
{
int i;
string temp;
if(top==-1)
{
cout<<"stack underflow!!\n";
return "abc";
}
temp = item[top];
top--;
return temp;
}
};
int main(int argc, char** argv)
{
int i;
stack st;
string prefix;
cout<<"Enter valid prefix string: ";
cin>>prefix;
for(i=prefix.size()-1;i>=0;i--)
{
if(prefix[i]=='+' || prefix[i]=='-' || prefix[i]=='*' || prefix[i]=='/' || prefix[i]=='^')
{
string op1,op2,temp;
op1=st.pop();
op2=st.pop();
temp='('+op1+prefix[i]+op2+')';
st.push(temp);
}
else
{
string flag;
flag=flag+prefix[i];
st.push(flag);
}
}
cout<<"The resultant infix string is: "<<st.pop();
return 0;
}
```
```OUTPUT:
Enter valid Prefix String: +a/*bc-de
The resultant infix string: (a+((b*c)/(d-e)))```

Related Posts: