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) {
return (opening == '(' && closing == ')') ||
(opening == '[' && closing == ']') ||
(opening == '{' && closing == '}');
} }
int are_parentheses_balanced(char expr[]) { int isMatching(char c1, char c2) {
int i; if (c1 == '(' && c2 == ')')
for (i = 0; expr[i] != '\0'; i++) { return 1;
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') { if (c1 == '[' && c2 == ']')
push(expr[i]); return 1;
} else if (expr[i] == ')' || expr[i] == ']' || expr[i] == '}') { if (c1 == '{' && c2 == '}')
if (top == -1 || !is_matching_pair(pop(), expr[i])) { return 1;
return 0;
}
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 0;
} }
} }
if (top == -1)
return 1;
else
return 0;
} }
return (top == -1);
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;
} }