C Exercises: Check a parentheses string is balanced or not using stack
7. Balanced Parentheses and Delimiters
Write a C program that checks whether a string of parentheses is balanced or not using stack.
An opening symbol that has a corresponding closing symbol is considered balanced parentheses, where the parentheses are correctly nested and the opening and closing symbols are the same.
- Valid balanced parentheses:
- [ [ { { ( ( ) ) } } ] ]
- [ ] [ ] [ ] ( ) { }
- Invalid balanced parentheses:
- ( [ ) ]
- ( ( ( ) ] ) )
- [ { ( ) ]
Sample Solution:
C Code:
Output:
Input an expression in parentheses: {[]) The expression is not balanced. ----------------------------------------- Input an expression in parentheses: ((())) The expression is balanced. ----------------------------------------- Input an expression in parentheses: ()) The expression is not balanced. ----------------------------------------- Input an text of parentheses: ([]){}[[(){}]{}] The expression is balanced. ----------------------------------------- Input an expression in parentheses: [(])) The expression is not balanced.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to check if an expression containing curly braces, square brackets, and parentheses is balanced.
- Write a C program to validate /XML tag pairs using stack operations.
- Write a C program to check for balanced parentheses and indicate the position of the first mismatch.
- Write a C program to support custom delimiter pairs and verify if a given expression is balanced using a stack.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Sort a stack using another stack.
Next: Next greater for each element in an array using a stack.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.