Hello friends!!!!!
Infix to Postfix Expression
#include <stdio.h>
#include <stdlib.h>
#include<ctype.h>
//Definition section
#define MAX 100
// Initialising the Stack structure
struct stack {
int arr[MAX];
int top;
};
typedef struct stack Stack;
// Function to initialize the stack
void initialisation(Stack* s) {
s->top = -1;
}
// Function that check whether the stack is full or not
int isFull(Stack* s) {
return s->top == MAX - 1;
}
// Function to check if the stack is empty
int isEmpty(Stack* s) {
return s->top == -1;
}
// push operation
void push(Stack* s, int value) {
if (isFull(s)) {
printf("Stack overflow!\n");
} else {
s->arr[++s->top] = value;
}
}
// pop function
int pop(Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
return -1;
} else {
int popped_Value = s->arr[s->top--];
return popped_Value;
}
}
// Function to get peek value
int peek(Stack* s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
} else {
return s->arr[s->top];
}
}
//display - function
void display(Stack* s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
} else {
printf("Stack elements: ");
for (int i = s->top; i >= 0; i--) {
printf("%d ", s->arr[i]);
}
printf("\n");
}
}
int precedence_of_operators(char op)
{
switch (op)
{
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
default: return 0;
}
}
//infix to postfix conversion
void infix_to_postfix(char exp, char postfix_exp)
{
int i, j;
char c;
Stack s;
initialisation(&s);
for(i=0, j=0; exp[i] != '\0'; i++)
{
c = exp[i];
if(isalnum(c))
{
postfix_exp[j++] = c;
}
else if(c == '(')
{
push(&s, c);
}
else if(c == ')')
{
while (!isEmpty(&s) && peek(&s) != '(')
{
postfix_exp[j++] = (char)pop(&s);
}
pop(&s);
}
else
{
while( !isEmpty(&s) && precedence_of_operators((char)peek(&s)) >= precedence_of_operators(c))
{
postfix_exp[j++] = (char)pop(&s);
}
push(&s, c);
}
}
while (!isEmpty(&s))
{
postfix_exp[j++] = (char)pop(&s);
}
postfix_exp[j] = '\0';
}
int main() {
char expression[MAX], postfix_exp[MAX];
printf("Enter an infix expression: ");
scanf("%s", expression);
infix_to_postfix(expression, postfix_exp);
printf("Postfix expression: %s\n", postfix_exp);
return 0;
}