Infix to Postfix Converter || C++
In this, we are going to see a program on Infix to Postfix Conversion using stack in C++ Programming Language.



The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <ctype.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>

int top;
char stack[10];
char res[20], s[20];
int prec(char c)
{
    if (c == '/' || c == '*')
        return 3;
    else if (c == '+' || c == '-')
        return 2;
    else if (c == '(')
        return 1;
    else
        return -1;
}

void push(char x)
{
    top++;
    stack[top] = x;
}

char pop()
{
    if (top == -1)
    {
        return -1;
    }
    else
    {
        return stack[top--];
    }
}

void main()
{
    top = -1;
    int i;
    char elem;

    cout << "Enter Infix expression: ";

    cin >> s;
    cout << "The Postfix expression: ";

    for (i = 0; i < strlen(s); i++)
    {
        elem = s[i];
        if (isalnum(elem))
        {
            cout << elem;
        }

        else if (elem == '(')
        {
            push(elem);
        }

        else if (elem == ')')
        {
            char x;
            while ((x = pop()) != '(')
            {
                cout << elem;
            }
        }
        else
        {
            while (top != -1 && prec(stack[top]) >= prec(elem))
            {
                cout << pop();
            }
            push(elem);
        }
    }
    while (top > -1)
    {
        cout << pop();
    }
    getch();
    clrscr();
}

The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
#include <string.h>
using namespace std;

int top;
char stack[10];
char res[20], s[20];
int prec(char c)
{
    if (c == '/' || c == '*')
        return 3;
    else if (c == '+' || c == '-')
        return 2;
    else if (c == '(')
        return 1;
    else
        return -1;
}

void push(char x)
{
    top++;
    stack[top] = x;
}

char pop()
{
    if (top == -1)
    {
        return -1;
    }
    else
    {
        return stack[top--];
    }
}

int main()
{
    top = -1;
    int i;
    char elem;

    cout << "Enter Infix expression: ";

    cin >> s;
    cout << "The Postfix expression: ";

    for (i = 0; i < strlen(s); i++)
    {
        elem = s[i];
        if (isalnum(elem))
        {
            cout << elem;
        }

        else if (elem == '(')
        {
            push(elem);
        }

        else if (elem == ')')
        {
            char x;
            while ((x = pop()) != '(')
            {
                cout << elem;
            }
        }
        else
        {
            while (top != -1 && prec(stack[top]) >= prec(elem))
            {
                cout << pop();
            }
            push(elem);
        }
    }
    while (top > -1)
    {
        cout << pop();
    }
    return 0;
}


#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post