0% found this document useful (0 votes)
5 views

EXp 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

EXp 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

//Atharva Pashilkar

//SE-A COMPS -59


#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define MAX 100

char a[MAX];
int top = -1;

void push(char a[], char e);


char pop(char a[]);
void InfToPost(char s[], char t[]);
int priority(char op);

int main() {
char inf[MAX], post[MAX];
printf("Enter elements of infix:");
scanf("%s", inf);
InfToPost(inf, post);
printf("Postfix expression:");
puts(post);
return 0;
}

void InfToPost(char s[], char t[]) {


int i = 0, j = 0;

strcpy(t, "");
while (s[i] != '\0') {
if (s[i] == '(') {
push(a, s[i]);
i++;
}
else if (s[i] == ')') {
while (top != -1 && a[top] != '(') {
t[j] = pop(a);
j++;
}
if (top == -1) {
printf("INCORRECT EXPRESSION");
exit(1);
}

}
else if (isdigit(s[i]) || isalpha(s[i])) {
t[j] = s[i];
j++;
i++;
}
else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'
|| s[i] == '%') {
while (top != -1 && a[top] != '(' && priority(a[top]) >=
priority(s[i])) {
t[j] = pop(a);
j++;
}
push(a, s[i]);
i++;
}
else {
printf("Incorrect element in expression");
exit(1);
}
}
while (top != -1 && a[top] != '(') {
t[j] = pop(a);
j++;
}
t[j] = '\0';
}

int priority(char op) {


if (op == '/' || op == '*' || op == '%')
return 2;
else if (op == '+' || op == '-')
return 1;
else
return 0;
}

void push(char a[], char e) {


if (top == MAX - 1)
printf("OVERFLOW");
else {
top++;
a[top] = e;
}
}

char pop(char a[]) {


char e = ' ';
if (top == -1)
printf("UNDERFLOW");
else {
e = a[top];
top--;
}
return e;
}

You might also like