2024-08-05 01:10:12 +05:30
|
|
|
#include <stdio.h>
|
2024-08-07 17:07:48 +05:30
|
|
|
#include <string.h>
|
|
|
|
|
2024-08-05 01:10:12 +05:30
|
|
|
#define MAX_SIZE 100
|
|
|
|
|
|
|
|
int top = -1;
|
2024-08-07 17:07:48 +05:30
|
|
|
char stack[MAX_SIZE];
|
2024-08-05 01:10:12 +05:30
|
|
|
|
2024-08-07 17:07:48 +05:30
|
|
|
void push(char value) {
|
|
|
|
if (top == MAX_SIZE - 1) {
|
|
|
|
printf("Stack is full\n");
|
|
|
|
return;
|
2024-08-05 01:10:12 +05:30
|
|
|
}
|
2024-08-07 17:07:48 +05:30
|
|
|
stack[++top] = value;
|
2024-08-05 01:10:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
char pop() {
|
2024-08-07 17:07:48 +05:30
|
|
|
if (top == -1) {
|
|
|
|
printf("Stack is empty\n");
|
|
|
|
return '\0';
|
2024-08-05 01:10:12 +05:30
|
|
|
}
|
2024-08-07 17:07:48 +05:30
|
|
|
return stack[top--];
|
2024-08-05 01:10:12 +05:30
|
|
|
}
|
|
|
|
|
2024-08-07 17:07:48 +05:30
|
|
|
int isMatching(char c1, char c2) {
|
|
|
|
if (c1 == '(' && c2 == ')')
|
|
|
|
return 1;
|
|
|
|
if (c1 == '[' && c2 == ']')
|
|
|
|
return 1;
|
|
|
|
if (c1 == '{' && c2 == '}')
|
|
|
|
return 1;
|
|
|
|
return 0;
|
2024-08-05 01:10:12 +05:30
|
|
|
}
|
|
|
|
|
2024-08-07 17:07:48 +05:30
|
|
|
int isParenthesisBalanced(char* expression) {
|
|
|
|
for (int i = 0; i < strlen(expression); i++) {
|
|
|
|
char c = expression[i];
|
|
|
|
|
|
|
|
if (c == '(' || c == '[' || c == '{')
|
|
|
|
push(c);
|
|
|
|
|
|
|
|
if (c == ')' || c == ']' || c == '}') {
|
|
|
|
char pop_value = pop();
|
|
|
|
|
|
|
|
if (!isMatching(pop_value, c))
|
2024-08-05 01:10:12 +05:30
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
2024-08-07 17:07:48 +05:30
|
|
|
|
|
|
|
if (top == -1)
|
|
|
|
return 1;
|
|
|
|
else
|
|
|
|
return 0;
|
|
|
|
}
|
2024-08-05 01:10:12 +05:30
|
|
|
|
|
|
|
int main() {
|
2024-08-07 17:07:48 +05:30
|
|
|
char expression[MAX_SIZE];
|
2024-08-05 01:10:12 +05:30
|
|
|
printf("Enter an expression: ");
|
2024-08-07 17:07:48 +05:30
|
|
|
scanf("%s", expression);
|
2024-08-05 01:10:12 +05:30
|
|
|
|
2024-08-07 17:07:48 +05:30
|
|
|
if (isParenthesisBalanced(expression))
|
|
|
|
printf("Expression is balanced\n");
|
|
|
|
else
|
|
|
|
printf("Expression is not balanced\n");
|
2024-08-05 01:10:12 +05:30
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|