-
Notifications
You must be signed in to change notification settings - Fork 0
/
2. Check for balanced parentheses in an expression.c
113 lines (96 loc) · 2.52 KB
/
2. Check for balanced parentheses in an expression.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
/**********************************************************************************************************
TITLE: Check for balanced parentheses in an expression.
**********************************************************************************************************/
//extension of matching of nested parentheses
//( ) parentheses
//[ ] brackets
//{} braces
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 20
typedef struct
{
char a[SIZE];
int tos;
}Stack;
void push (Stack *p,double x)
{
p->tos++;
p->a[p->tos]=x;
}
//Pop Function
char pop(Stack *p)
{
return(p->a[p->tos--]);
}
int main()
{
Stack s1;
char exp[SIZE];
int i;
s1.tos=-1; //Initializing the top of stack to -1
printf("\nEnter an expression:\n");
gets(exp); //Taking the expression to be checked from user
char bracket;
for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='('||exp[i]=='{'||exp[i]=='[') //Condition for opening bracket
{
push(&s1,exp[i]); //Pushing the opening bracket
}
else if(exp[i]==')'||exp[i]=='}'||exp[i]==']') //condition for closing brackets
{
if(s1.tos != -1)
{
bracket = pop(&s1);
switch(exp[i])
{
case ')':
if( bracket == '{' || bracket == '[' )
{
printf("\nCorresponding '(' missing");
exit(0);
}
break;
case ']':
if( bracket == '{' || bracket == '(' )
{
printf("\nCorresponding '[' missing");
exit(0);
}
break;
case '}':
if( bracket == '(' || bracket == '[' )
{
printf("\nCorresponding '{' missing");
exit(0);
}
}
}
else
{ //if stack is empty
printf("\nCorresponding '(' or '{' or '[' missing"); // does not have a corresponding opening bracket/parentheses/braces
exit(0); // exit from program execution with return status as 0
}
}
}
/*After traversing entire string*/
if(s1.tos != -1) //check if stack is not empty
printf("\nCorresponding ')' or '}' or ']' missing");
else //if stack is empty
printf("\nMatched"); //equal no of brackets
return 0;
}
/**************************************************************************************************
OUTPUT:
Test Case 1:
Enter an expression: (a+b)*(c+d)
Matched
Test Case 2:
Enter an expression:{a+(b+c})
Corresponding '{' missing
Test Case 3:
Enter an expression:{[)]
Corresponding '(' missing
***************************************************************************************************/