From 5065f1f758afda45e269c9e573facf502a59887a Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Wed, 7 Aug 2024 17:07:48 +0530 Subject: [PATCH] Update DS/C/Lab/Week3/Parenthesis.c --- DS/C/Lab/Week3/Parenthesis.c | 70 ++++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/DS/C/Lab/Week3/Parenthesis.c b/DS/C/Lab/Week3/Parenthesis.c index fa2880b..185cebc 100644 --- a/DS/C/Lab/Week3/Parenthesis.c +++ b/DS/C/Lab/Week3/Parenthesis.c @@ -1,51 +1,67 @@ #include +#include + #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; }