C program to check for balanced parentheses using Stack:
Let us create a c program for balance parentheses. It uses Stack for expression evaluation.
Program implementation:
This program includes the built-in
header files. It defines the MAX value
as 50.
- let us create a stack of MAX size. Initialise the value as -1.
- Create functions push(),pop(),isMatching(),is_Balanced().
- ‘push()’ – it takes a data and insert into the stack. It checks the top value is equals to MAX-1. If it is equal. Then print the stack is overflow. Otherwise, it inserts the value into stack.
- ‘pop()’ – it deletes the data. It checks the top value is equal to -1. If yes, it returns 0.otherwise, it returns the top value.
- ‘isMatching()’ – it takes input as two characters. The characters are checked with characters like ‘(‘,’)’,’{‘,’}’,’[‘,’]’.
- ‘is_Balanced()’ - it reads an expression. It separates the parenthesis of any type and stores in the stack. It uses ‘isMatching()’ function to check for match. If it matches, the expression is balanced.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
// let us implement the Stack
char stack[MAX];
int top = -1;
void push(char d) {
if (top == MAX -
1) {
printf("Stack is overflow\n");
exit(1);
}
stack[++top] = d;
}
char pop() {
if (top == -1) {
return '\0';
// Empty stack
}
return
stack[top--];
}
int isMatching(char l, char r) {
return (l == '('
&& r == ')') ||
(l == '{'
&& r == '}') ||
(l == '['
&& r == ']');
}
int is_Balanced(char *exp) {
for (int i = 0; i
< strlen(exp); i++) {
char c =
exp[i];
if (c == '('
|| c == '{' || c == '[') {
push(c);
} else if (c
== ')' || c == '}' || c == ']') {
char
popped = pop();
if
(!isMatching(popped, c)) {
return
0; // Not balanced
}
}
}
return (top ==
-1); // Balanced if stack is empty
}
int main() {
char exp[MAX];
printf("Enter
an expression: ");
scanf("%s", exp);
if
(is_Balanced(exp)) {
printf("Balanced\n");
} else {
printf("Not Balanced\n");
}
return 0;
}
Output:
Enter an expression: r+(t+y)+(h
Not Balanced
Enter an expression: a+(b*c)
Balanced
That’s all. The C program is successful to check the balance
of parenthesis using Stack. Hope, this code will help you. Keep coding!!!
Comments
Post a Comment