Upload files to "DS/C/Lab/Week6"
This commit is contained in:
parent
0cdc830d54
commit
c6df50662d
4 changed files with 287 additions and 0 deletions
70
DS/C/Lab/Week6/PrefixCheck.c
Normal file
70
DS/C/Lab/Week6/PrefixCheck.c
Normal file
|
@ -0,0 +1,70 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_SIZE 100
|
||||
|
||||
int stack[MAX_SIZE];
|
||||
int top = -1;
|
||||
|
||||
void push(int item) {
|
||||
if (top >= MAX_SIZE - 1) {
|
||||
printf("Stack Overflow\n");
|
||||
return;
|
||||
}
|
||||
stack[++top] = item;
|
||||
}
|
||||
|
||||
int pop() {
|
||||
if (top < 0) {
|
||||
printf("Stack Underflow\n");
|
||||
return -1;
|
||||
}
|
||||
return stack[top--];
|
||||
}
|
||||
|
||||
int isOperator(char c) {
|
||||
return (c == '+' || c == '-' || c == '*' || c == '/');
|
||||
}
|
||||
|
||||
int isDigit(char c) {
|
||||
return (c >= '0' && c <= '9');
|
||||
}
|
||||
|
||||
int evaluatePrefix(char* expr) {
|
||||
int len = strlen(expr);
|
||||
for (int i = len - 1; i >= 0; i--) {
|
||||
if (isDigit(expr[i])) {
|
||||
push(expr[i] - '0');
|
||||
} else if (isOperator(expr[i])) {
|
||||
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 '/':
|
||||
if (operand2 != 0) push(operand1 / operand2);
|
||||
else {
|
||||
printf("Error: Division by zero\n");
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return pop();
|
||||
}
|
||||
|
||||
int main() {
|
||||
char expr[MAX_SIZE];
|
||||
printf("Enter prefix expression: ");
|
||||
fgets(expr, MAX_SIZE, stdin);
|
||||
expr[strcspn(expr, "\n")] = 0; // Remove newline if present
|
||||
|
||||
int result = evaluatePrefix(expr);
|
||||
if (result != -1) {
|
||||
printf("Result: %d\n", result);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue