-
Notifications
You must be signed in to change notification settings - Fork 10
/
balanced_parentheses_checker.c
131 lines (119 loc) · 2.35 KB
/
balanced_parentheses_checker.c
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// program to check whether a given expression contains balanced parantheses.
/*
Examples:
{}{} : balanced.
{{]] : not balanced.
}{ : not balanced.
()()(: not balanced.
5{ : not balanced.
{[()]}: balanced.
*/
// program to check whether a given expression contains balanced parentheses.
#include <stdio.h>
#include <stdlib.h>
#define stacksize 50
// utility functions
int expr_size(char expression[]);
void push(char ch);
// main functions
int parentheses_check(char expression[]);
void check(char exp[]);
// driver function
int main()
{
// example
char exp[] = "{[9*(5+4)+(7^2)]/[99*5]}";
check(exp);
return 0;
}
// declaring stack to check parentheses
char stack[stacksize];
int top = -1;
// FUNCTIONS:
// utility functions
int expr_size(char expression[])
{
int size = 0;
while (expression[size] != '\0')
{
size++;
}
return size;
}
void push(char ch)
{
if (top < stacksize)
{
stack[++top] = ch;
}
else
{
printf("OOF! stackoverflow.");
}
}
// main parentheses checker function
int parentheses_check(char expression[])
{
int size = expr_size(expression);
for (int i = 0; i < size; i++)
{
if (expression[i] == '{' || expression[i] == '(' || expression[i] == '[')
{
push(expression[i]);
}
else if (expression[i] == '}')
{
if (stack[top] == '{')
{
top--;
}
else
{
return 0;
}
}
else if (expression[i] == ']')
{
if (stack[top] == '[')
{
top--;
}
else
{
return 0;
}
}
else if (expression[i] == ')')
{
if (stack[top] == '(')
{
top--;
}
else
{
return 0;
}
}
}
if (top == -1)
{
return 1;
}
else
{
return 0;
}
}
// tells the user whether the given expression has balanced parentheses or not
void check(char exp[])
{
int checkvar = parentheses_check(exp);
if (checkvar)
{
printf("parentheses Are Balanced");
}
else
{
printf("Not balanced! Recheck parentheses.");
}
}