Week 2:
Infix to Postfix Expression Converter:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// Stack implementation
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
if (s->top < MAX_SIZE - 1) {
s->items[++(s->top)] = c;
}
}
char pop(Stack *s) {
if (s->top >= 0) {
return s->items[(s->top)--];
}
return '\0';
}
char peek(Stack *s) {
if (s->top >= 0) {
return s->items[s->top];
}
return '\0';
}
int isEmpty(Stack *s) {
return s->top == -1;
}
// Function to check if character is an operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Function to get operator precedence
int precedence(char c) {
switch (c) {
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}
// Function to convert infix to postfix
void infixToPostfix(char *infix, char *postfix) {
Stack stack;
initStack(&stack);
int i, j;
i = j = 0;
while (infix[i] != '\0') {
char c = infix[i];
// If character is operand, add to output
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <=
'9')) {
postfix[j++] = c;
}
// If character is '(', push to stack
else if (c == '(') {
push(&stack, c);
}
// If character is ')', pop and output until '(' is found
else if (c == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
if (!isEmpty(&stack) && peek(&stack) == '(') {
pop(&stack); // Remove '('
}
}
// If character is operator
else if (isOperator(c)) {
while (!isEmpty(&stack) && peek(&stack) != '(' &&
((c != '^' && precedence(peek(&stack)) >= precedence(c)) ||
(c == '^' && precedence(peek(&stack)) > precedence(c)))) {
postfix[j++] = pop(&stack);
}
push(&stack, c);
}
i++;
}
// Pop remaining operators from stack
while (!isEmpty(&stack)) {
if (peek(&stack) == '(') {
pop(&stack);
} else {
postfix[j++] = pop(&stack);
}
}
postfix[j] = '\0';
}
int main() {
char infix[MAX_SIZE];
char postfix[MAX_SIZE];
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("%s\n", postfix);
return 0;
}
Infix to Prefix Expression Converter
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack implementation
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
void initialize(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
s->items[++(s->top)] = c;
}
char pop(Stack *s) {
return s->items[(s->top)--];
}
char peek(Stack *s) {
return s->items[s->top];
}
int isEmpty(Stack *s) {
return s->top == -1;
}
// Function to check if character is an operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Function to get operator precedence
int precedence(char c) {
switch(c) {
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}
// Function to reverse string
void reverseString(char *str) {
int i, j;
char temp;
for(i = 0, j = strlen(str)-1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
// Function to convert infix to prefix
void infixToPrefix(char *infix, char *prefix) {
Stack stack;
initialize(&stack);
// Reverse infix expression
reverseString(infix);
// Process each character
int i, j = 0;
int len = strlen(infix);
for(i = 0; i < len; i++) {
char c = infix[i];
// If operand, add to output
if(c >= '0' && c <= '9') {
prefix[j++] = c;
}
// If right parenthesis, push to stack
else if(c == ')') {
push(&stack, c);
}
// If left parenthesis, pop until right parenthesis
else if(c == '(') {
while(!isEmpty(&stack) && peek(&stack) != ')') {
prefix[j++] = pop(&stack);
}
if(!isEmpty(&stack)) {
pop(&stack); // Remove '('
}
}
// If operator
else if(isOperator(c)) {
while(!isEmpty(&stack) &&
peek(&stack) != ')' &&
precedence(c) < precedence(peek(&stack))) {
prefix[j++] = pop(&stack);
}
push(&stack, c);
}
}
// Pop remaining operators
while(!isEmpty(&stack)) {
prefix[j++] = pop(&stack);
}
prefix[j] = '\0';
// Reverse the final string
reverseString(prefix);
}
int main() {
char infix[MAX_SIZE];
char prefix[MAX_SIZE];
// Read input
scanf("%s", infix);
// Convert to prefix
infixToPrefix(infix, prefix);
// Print result
printf("%s", prefix);
return 0;
}
Postfix to Fully Parenthesized Infix Expression
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100
#define MAX_EXPR 200
// Stack structure to store expressions
typedef struct {
char* items[MAX_SIZE];
int top;
} Stack;
// Initialize stack
void initialize(Stack* s) {
s->top = -1;
}
// Push operation
void push(Stack* s, char* expr) {
s->items[++(s->top)] = strdup(expr);
}
// Pop operation
char* pop(Stack* s) {
if (s->top == -1) return NULL;
return s->items[(s->top)--];
}
// Check if character is operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Convert postfix to infix
void postfixToInfix(char* postfix) {
Stack stack;
initialize(&stack);
char* token = strtok(postfix, " ");
char expr[MAX_EXPR];
while (token != NULL) {
// If token is an operand, push to stack
if (!isOperator(token[0])) {
push(&stack, token);
}
// If token is an operator
else {
char* op2 = pop(&stack);
char* op1 = pop(&stack);
// Create new expression with parentheses
sprintf(expr, "(%s%c%s)", op1, token[0], op2);
push(&stack, expr);
// Free the popped expressions
free(op1);
free(op2);
}
token = strtok(NULL, " ");
}
// Print final expression
char* result = pop(&stack);
printf("%s\n", result);
free(result);
// Free any remaining items in stack
while (stack.top >= 0) {
free(stack.items[stack.top--]);
}
}
int main() {
char postfix[MAX_SIZE];
// Read input
fgets(postfix, MAX_SIZE, stdin);
// Remove trailing newline if present
int len = strlen(postfix);
if (postfix[len-1] == '\n') {
postfix[len-1] = '\0';
}
// Convert and print result
postfixToInfix(postfix);
return 0;
}
Prefix to Fully Parenthesized Infix Expression
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100
#define MAX_EXPR 200
// Stack structure to store expressions
typedef struct {
char* items[MAX_SIZE];
int top;
} Stack;
// Initialize stack
void initialize(Stack* s) {
s->top = -1;
}
// Push operation
void push(Stack* s, char* expr) {
s->items[++(s->top)] = strdup(expr);
}
// Pop operation
char* pop(Stack* s) {
if (s->top == -1) return NULL;
return s->items[(s->top)--];
}
// Check if character is operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Function to reverse tokens in expression
void reverseTokens(char* expr) {
char* tokens[MAX_SIZE];
int count = 0;
// Split into tokens
char* token = strtok(expr, " ");
while (token != NULL) {
tokens[count++] = strdup(token);
token = strtok(NULL, " ");
}
// Rebuild expression in reverse
expr[0] = '\0';
for (int i = count - 1; i >= 0; i--) {
strcat(expr, tokens[i]);
if (i > 0) strcat(expr, " ");
free(tokens[i]);
}
}
// Convert prefix to infix
void prefixToInfix(char* prefix) {
Stack stack;
initialize(&stack);
// Reverse the expression first
reverseTokens(prefix);
char* token = strtok(prefix, " ");
char expr[MAX_EXPR];
while (token != NULL) {
// If token is an operand, push to stack
if (!isOperator(token[0])) {
push(&stack, token);
}
// If token is an operator
else {
char* op1 = pop(&stack);
char* op2 = pop(&stack);
// Create new expression with parentheses
sprintf(expr, "(%s%c%s)", op1, token[0], op2);
push(&stack, expr);
// Free the popped expressions
free(op1);
free(op2);
}
token = strtok(NULL, " ");
}
// Print final expression
char* result = pop(&stack);
printf("%s\n", result);
free(result);
// Free any remaining items in stack
while (stack.top >= 0) {
free(stack.items[stack.top--]);
}
}
int main() {
char prefix[MAX_SIZE];
// Read input
fgets(prefix, MAX_SIZE, stdin);
// Remove trailing newline if present
int len = strlen(prefix);
if (prefix[len-1] == '\n') {
prefix[len-1] = '\0';
}
// Convert and print result
prefixToInfix(prefix);
return 0;
}
Evaluate Postfix Expression
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// Stack structure
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
// Initialize stack
void initialize(Stack* s) {
s->top = -1;
}
// Push operation
void push(Stack* s, int value) {
s->items[++(s->top)] = value;
}
// Pop operation
int pop(Stack* s) {
if (s->top == -1) return -1;
return s->items[(s->top)--];
}
// Check if character is operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
// Evaluate postfix expression
void evaluatePostfix(char* postfix) {
Stack stack;
initialize(&stack);
char* token = strtok(postfix, " ");
while (token != NULL) {
// If token is an operand
if (!isOperator(token[0])) {
push(&stack, atoi(token));
}
// If token is an operator
else {
int op2 = pop(&stack);
int op1 = pop(&stack);
switch(token[0]) {
case '+':
push(&stack, op1 + op2);
break;
case '-':
push(&stack, op1 - op2);
break;
case '*':
push(&stack, op1 * op2);
break;
case '/':
if (op2 == 0) {
printf("Division by zero\n");
return;
}
push(&stack, op1 / op2);
break;
}
}
token = strtok(NULL, " ");
}
// Print final result
printf("%d\n", pop(&stack));
}
int main() {
char postfix[MAX_SIZE];
// Read input
fgets(postfix, MAX_SIZE, stdin);
// Remove trailing newline if present
int len = strlen(postfix);
if (postfix[len-1] == '\n') {
postfix[len-1] = '\0';
}
// Evaluate and print result
evaluatePostfix(postfix);
return 0;
}
Evaluate Prefix Expression
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int value) {
stack[++top] = value;
}
int pop() {
return stack[top--];
}
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int evaluatePrefix(char* expr) {
int len = strlen(expr);
// Find the rightmost token
int i;
for (i = len - 1; i >= 0; i--) {
if (expr[i] == ' ') continue;
if (isdigit(expr[i])) {
// If it's a digit, push to stack
push(expr[i] - '0');
}
else if (isOperator(expr[i])) {
// If it's an operator, pop two operands and perform operation
int operand1 = pop();
int operand2 = pop();
switch(expr[i]) {
case '+':
push(operand1 + operand2);
break;
case '-':
push(operand1 - operand2);
break;
case '*':
push(operand1 * operand2);
break;
case '/':
push(operand1 / operand2);
break;
}
}
}
return pop();
}
int main() {
char expr[MAX_SIZE];
// Read the input expression
fgets(expr, MAX_SIZE, stdin);
// Remove trailing newline if present
int len = strlen(expr);
if (expr[len-1] == '\n') {
expr[len-1] = '\0';
}
// Reset stack
top = -1;
// Evaluate and print result
printf("%d\n", evaluatePrefix(expr));
return 0;
}