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