Infix, Postfix and Tower of Hanoi

Infix expression

An expression written in infix notation has operators placed between operands, like A + B. To process this, an algorithm might first parse the input to ensure it follows precedence rules. Parentheses are used to define precedence explicitly, like in (A + B) * C. As the program reads the input, it identifies operators, operands, and brackets. Parentheses temporarily hold operations, and once closed, the computation for the enclosed part is performed. The flow of execution ensures the operator's priority is respected, moving through each character and interpreting it based on its position.

Postfix expression

In postfix expression, operators follow their operands, making evaluation straightforward. A stack is used to compute results. As the input is read, each character is checked—if it’s an operand, it is directly output. Operators are pushed onto the stack until their precedence is lower than the one already there, at which point they are popped and output. Parentheses aren’t required as the position defines priority. As each character is processed, operands and operators are handled separately, and the stack keeps track of operations to be completed, resulting in an easy-to-follow execution path.

Here is a C program to convert Infix Expression to postfix expression.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char stack[100];
int top=-1;
void push(char x);
char pop();
int priority(char x);
int main(){
    char exp[100],*e,x;
    printf("\n Enter the expression:");
    scanf("%s",exp);
    e=exp;
    printf("The output is:");
    while(*e!='\0'){
        if(isalnum(*e))//Cheaks if each character in the *e an alpha numeric
        {
            printf("%c",*e);
        }
        else if(*e=='('){
            push(*e);
        }
        else if(*e==')'){//Until ( open brakets keep on popping element and display popped element
            while((x=pop())!='('){
                printf("%c",x);
            }
        }
        //check the priority of the top element in the stack with the element in *e
        else{
            while(priority(stack[top])>=priority(*e))
            printf("%c",pop());
            push(*e);
        }
        e++;
    }
    while(top!=-1){//Prints and pops the elements left in the stack
        printf("%c",pop());
    }
    printf("\n");
    return 0;
}
void push(char x){

    top++;
    stack[top]=x;

}
char pop(){
    if(top==-1){
        printf("Stack underflow\n");
        return '\0';
    }

    return stack[top--];
}
int priority(char x){
    if(x=='(')
        return 0;
    if(x=='+'||x=='-')
        return 1;
    if(x=='*'||x=='/')
        return 2;
    if(x=='$'||x=='^')
        return 3;
    return 0;
}

First an array called Stack is taken, and push, pop, priority functions are defined. Another array called exp is taken and the character e is assigned the elements entered into exp. The while loop keeps on repeating itself until there is no element in e. The if statement checks if each character in the *e an alpha numeric. The 3’d if until ( open brackets keep on popping element and display popped element. The 2nd while check the priority of the top element in the stack with the element in *e. And e++ increases the e value and it keeps on moving forward, each character at a time. The last while prints and pops the elements left in the stack. The priority assigns values to each symbol.

Here is a program to evaluate postfix expression.

#include<stdio.h>
#include<ctype.h>
int stack[20];
int top=-1;
void push(int x)
{
    stack[++top]=x;
}
int pop(){
    return stack[top--];
}
int main(){
    char exp[20];
    char *e;
    int n1,n2,n3,num;
    printf("Enter the expression:\n");
    scanf("%s",exp);
    e=exp;
    while(*e!='\0')
    {
        if(isdigit(*e)){
            num=*e-'0';
            push(num);
        }
        else
        {
            n1=pop();
            n2=pop();
            switch (*e){
            {
                case '+':
                    n3=n1+n2;
                    break;
                }
                case '-':
                {
                    n3=n2-n1;
                    break;
                }
                case '*':
                {
                    n3=n1*n2;
                    break;
                }
                case '/':
                {
                    n3=n2/n1;
                    break;
                }

            }
            push(n3);
        }
        e++;
    }
    printf("\nThe result of expression %s=%d\n\n",exp,pop());
    return 0;
}
if(isdigit(*e))

It checks if the e value is a number. It assigns p1, p2 variable 2 pop functions. Based on the value of e it does the respective. The answers are stored in the variable p3 and it pushes p3.

Tower of Hanoi

The Tower of Hanoi is a puzzle that involves three rods and a number of disks of different sizes, stacked in decreasing order on one rod. The goal is to move the entire stack to another rod, following two rules: only one disk can be moved at a time, and a larger disk cannot be placed on top of a smaller disk. A recursive approach is used to solve the puzzle. First, the top n−1n-1 disks are moved to an auxiliary rod, then the largest disk is moved directly to the destination rod. Finally, the n−1n-1 disks are moved from the auxiliary rod to the destination rod. This process repeats for each disk, breaking the problem into smaller sub-problems until it’s solved.

This program shows a step by step way to solve the tower of hanoi.

#include<stdio.h>
void h(int n,char a, char b,char c);
static int step=0;
int main(){
    int n;
    printf("\nEnter the number of rings:");
    scanf("%d",&n);
    h(n,'a','b','c');
    return 0;
}
void h(int n,char a,char b,char c)
{
    if (n==1){
        printf("\n Step %d: move %d from %c to %c",++step,n,a,c);
    }
    else{
        h(n-1,a,c,b);
        h(1,a,b,c);
        h(n-1,b,a,c);
    }

}
if (n==1){
        printf("\n Step %d: move %d from %c to %c",++step,n,a,c);
    }
    else{
        h(n-1,a,c,b);
        h(1,a,b,c);
        h(n-1,b,a,c);
    }

When n==1 it prints the step name, the number of plates(n) and the name of the tower. In the else part it changes the value of n. The function calls itself.

Tower of Hanoi, 8 disks. Only 255 moves requires to solve it. - YouTube

Hope you learnt somethin new.

Happy Coding…