See Also:
C Program To Implement Postfix To Infix Conversion
C Program To Implement Postfix To Prefix Conversion
C Program To Implement Infix To Prefix Conversion
C Program To Implement Infix To Postfix Conversion
How To Evaluate Postfix Expressions
C Program To Evaluate Postfix Expression Using Array
C Program To Evaluate Postfix Expression Using Linked List
How To Balance The Given Expressions
C Program For Balancing Expressions Using Array
C Program For Balancing Expressions Using Linked List
C Program For Balancing Expressions (Parenthesis) Using Array:
C Program To Implement Postfix To Infix Conversion
C Program To Implement Postfix To Prefix Conversion
C Program To Implement Infix To Prefix Conversion
C Program To Implement Infix To Postfix Conversion
How To Evaluate Postfix Expressions
C Program To Evaluate Postfix Expression Using Array
C Program To Evaluate Postfix Expression Using Linked List
How To Balance The Given Expressions
C Program For Balancing Expressions Using Array
C Program For Balancing Expressions Using Linked List
#include <stdlib.h>
#include <string.h>
int top = -1;
int stack[100];
/* push the given data into the stack */
void push(int data) {
stack[++top] = data;
}
/* pop the top element from the stack */
int pop() {
int data;
if (top == -1)
return -1;
data = stack[top];
top--;
return (data);
}
int main() {
char str[100];
int i, flag = 0, data = 0;
/* get the expression from the user */
printf("Enter ur expression:");
fgets(str, 100, stdin);
for (i = 0; i < strlen(str); i++) {
/* open brace - push it into stack */
if (str[i] == '(' || str[i] == '{'
|| str[i] == '[') {
push(str[i]);
continue;
}
if (str[i] == ')' || str[i] == '}' || str[i] == ']') {
/* current char is close brace - so, POP */
data = pop();
if ((str[i] == ')' && data != '(') || data == -1 ||
(str[i] == '}' && data != '{') ||
(str[i] == ']' && data != '[')) {
/* no matching parenthesis */
flag = 1;
break;
}
}
}
if (flag == 1 || top > -1)
printf("Not a balanced expression\n");
else
printf("Balanced Expression\n");
return 0;
}
Output: (Balancing Parenthesis Example)
jp@jp-VirtualBox:$ ./a.out
Enter ur expression:(a+b)+{c+d(l-m)}
Balanced Expression
Enter ur expression:(a+b)+{c+d(l-m)}
Balanced Expression
No comments:
Post a Comment