-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced_exp.c
More file actions
88 lines (70 loc) · 1.75 KB
/
balanced_exp.c
File metadata and controls
88 lines (70 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define N 100
struct stack {
char data[N];
int top;
};
void initStack(struct stack *s) {
s->top = -1;
}
int isEmpty(struct stack *s) {
return s->top == -1;
}
int isFull(struct stack *s) {
return s->top == N - 1;
}
void push(struct stack *s, char c) {
if (isFull(s)) {
printf("Stack Overflow \n");
exit(1);
}
s->data[++(s->top)] = c;
}
char pop(struct stack *s) {
if (isEmpty(s)) {
return '\0';
}
return s->data[(s->top)--];
}
int isParenthesis(char c) {
return (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}');
}
int isMatchingPair(char opening, char closing) {
return (opening == '(' && closing == ')') || (opening == '[' && closing == ']') || (opening == '{' && closing == '}');
}
int isBalanced(char *expression) {
struct stack s;
initStack(&s);
for (int i = 0; expression[i] != '\0'; i++) {
char c = expression[i];
if (c == '(' || c == '[' || c == '{') {
push(&s, c);
}
else if (c == ')' || c == ']' || c == '}') {
if (isEmpty(&s)) {
printf("Closing bracket found without opening bracket. \n");
return 0;
}
char top = pop(&s);
if (!isMatchingPair(top, c)) {
printf("Parentheses do not match \n");
return 0;
}
}
}
return isEmpty(&s);
}
int main() {
char expression[N];
printf("Enter an expression: ");
scanf("%s", expression);
if (isBalanced(expression)) {
printf("The expression is balanced.\n");
}
else {
printf("The expression is not balanced.\n");
}
return 0;
}