Update DS/C/Lab/Week3/Parenthesis.c

This commit is contained in:
Aadit Agrawal 2024-08-07 17:07:48 +05:30
parent a033c5175f
commit 5065f1f758

View File

@ -1,51 +1,67 @@
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
char stack[MAX_SIZE];
int top = -1;
char stack[MAX_SIZE];
void push(char c) {
if (top < MAX_SIZE - 1) {
stack[++top] = c;
void push(char value) {
if (top == MAX_SIZE - 1) {
printf("Stack is full\n");
return;
}
stack[++top] = value;
}
char pop() {
if (top >= 0) {
return stack[top--];
if (top == -1) {
printf("Stack is empty\n");
return '\0';
}
return '\0';
return stack[top--];
}
int is_matching_pair(char opening, char closing) {
return (opening == '(' && closing == ')') ||
(opening == '[' && closing == ']') ||
(opening == '{' && closing == '}');
int isMatching(char c1, char c2) {
if (c1 == '(' && c2 == ')')
return 1;
if (c1 == '[' && c2 == ']')
return 1;
if (c1 == '{' && c2 == '}')
return 1;
return 0;
}
int are_parentheses_balanced(char expr[]) {
int i;
for (i = 0; expr[i] != '\0'; i++) {
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') {
push(expr[i]);
} else if (expr[i] == ')' || expr[i] == ']' || expr[i] == '}') {
if (top == -1 || !is_matching_pair(pop(), expr[i])) {
int isParenthesisBalanced(char* expression) {
for (int i = 0; i < strlen(expression); i++) {
char c = expression[i];
if (c == '(' || c == '[' || c == '{')
push(c);
if (c == ')' || c == ']' || c == '}') {
char pop_value = pop();
if (!isMatching(pop_value, c))
return 0;
}
}
}
return (top == -1);
if (top == -1)
return 1;
else
return 0;
}
int main() {
char expr[MAX_SIZE];
char expression[MAX_SIZE];
printf("Enter an expression: ");
scanf("%s", expr);
scanf("%s", expression);
if (are_parentheses_balanced(expr)) {
printf("Parentheses are balanced\n");
} else {
printf("Parentheses are not balanced\n");
}
if (isParenthesisBalanced(expression))
printf("Expression is balanced\n");
else
printf("Expression is not balanced\n");
return 0;
}