we
unknown
plain_text
10 months ago
3.0 kB
14
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// Stack for operators
char stack[MAX];
int top = -1;
void push(char c) {
stack[++top] = c;
}
char pop() {
return stack[top--];
}
char peek() {
return stack[top];
}
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char op) {
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
// Convert infix to postfix
void infixToPostfix(char* infix, char postfix[][10], int* pIndex) {
char token[10];
int i = 0, j = 0, k = 0;
while (infix[i] != '\0') {
if (infix[i] == ' ') {
i++;
continue;
}
// If operand
if (isalnum(infix[i])) {
j = 0;
while (isalnum(infix[i])) {
token[j++] = infix[i++];
}
token[j] = '\0';
strcpy(postfix[(*pIndex)++], token);
}
// If '('
else if (infix[i] == '(') {
push(infix[i]);
i++;
}
// If ')'
else if (infix[i] == ')') {
while (top != -1 && peek() != '(') {
token[0] = pop();
token[1] = '\0';
strcpy(postfix[(*pIndex)++], token);
}
pop(); // remove '('
i++;
}
// If operator
else if (isOperator(infix[i])) {
while (top != -1 && precedence(peek()) >= precedence(infix[i])) {
token[0] = pop();
token[1] = '\0';
strcpy(postfix[(*pIndex)++], token);
}
push(infix[i]);
i++;
}
}
// Pop remaining operators
while (top != -1) {
token[0] = pop();
token[1] = '\0';
strcpy(postfix[(*pIndex)++], token);
}
}
// Generate TAC from postfix
void generateTAC(char postfix[][10], int count) {
char tempVar[5];
char stack2[MAX][10];
int top2 = -1;
int tempCount = 1;
for (int i = 0; i < count; i++) {
if (isOperator(postfix[i][0]) && postfix[i][1] == '\0') {
char op2[10], op1[10], result[10];
strcpy(op2, stack2[top2--]);
strcpy(op1, stack2[top2--]);
sprintf(tempVar, "t%d", tempCount++);
printf("%s = %s %c %s\n", tempVar, op1, postfix[i][0], op2);
strcpy(stack2[++top2], tempVar);
} else {
strcpy(stack2[++top2], postfix[i]);
}
}
}
int main() {
char infix[100];
char postfix[50][10];
int pIndex = 0;
printf("Enter infix expression (e.g., a + b * c):\n");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = '\0'; // Remove newline
infixToPostfix(infix, postfix, &pIndex);
printf("\nIntermediate Code (Three Address Code):\n");
generateTAC(postfix, pIndex);
return 0;
}
Editor is loading...
Leave a Comment