-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek7.cpp
More file actions
55 lines (47 loc) · 974 Bytes
/
Copy pathweek7.cpp
File metadata and controls
55 lines (47 loc) · 974 Bytes
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
// In a class room we have discussed the stack operations called push() and pop(). Based on these operations design and implement the solution to identify the balanced and un-balanced expressions.
#include <iostream>
#include<stack>
using namespace std;
bool
isbalanced (string exp)
{
stack < char >stack;
for (char ch:exp)
{
if (ch == '(' || ch == '{' || ch == '[')
{
stack.push (ch);
}
if (ch == ')' || ch == '}' || ch == ']')
{
if (stack.empty ())
{
return false;
}
char top = stack.top ();
stack.pop ();
if ((top == '(' && ch != ')') || (top == '{' && ch != '}')
|| (top == '[' && ch != ']'))
{
return false;
}
}
}
return stack.empty ();
}
int
main ()
{
string exp;
cout << "Enter a expression:";
cin >> exp;
if (isbalanced (exp))
{
cout << "Expression Balanced" << endl;
}
else
{
cout << "Expression Not Balanced" << endl;
}
return 0;
}