w3resource

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:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100

// Global variables for stack and top
char stack[MAX_SIZE];
int top = -1;

// Function to push a character onto the stack
void push(char data) {
    if (top == MAX_SIZE - 1) {
        printf("Overflow stack!\n");
        return;
    }
    top++;
    stack[top] = data;
}

// Function to pop a character from the stack
char pop() {
    if (top == -1) {
        printf("Empty stack!\n");
        return ' ';
    }
    char data = stack[top];
    top--;
    return data;
}

// Function to check if two characters form a matching pair of parentheses
int is_matching_pair(char char1, char char2) {
    if (char1 == '(' && char2 == ')') {
        return 1;
    } else if (char1 == '[' && char2 == ']') {
        return 1;
    } else if (char1 == '{' && char2 == '}') {
        return 1;
    } else {
        return 0;
    }
}

// Function to check if the expression is balanced
int isBalanced(char* text) {
    int i;
    for (i = 0; i < strlen(text); i++) {
        if (text[i] == '(' || text[i] == '[' || text[i] == '{') {
            push(text[i]);
        } else if (text[i] == ')' || text[i] == ']' || text[i] == '}') {
            if (top == -1) {
                return 0; // If no opening bracket is present
            } else if (!is_matching_pair(pop(), text[i])) {
                return 0; // If closing bracket doesn't match the last opening bracket
            }
        }
    }
    if (top == -1) {
        return 1; // If the stack is empty, the expression is balanced
    } else {
        return 0; // If the stack is not empty, the expression is not balanced
    }
}

// Main function
int main() {
   char text[MAX_SIZE];
   printf("Input an expression in parentheses: ");
   scanf("%s", text);

   // Check if the expression is balanced or not
   if (isBalanced(text)) {
       printf("The expression is balanced.\n");
   } else {
       printf("The expression is not balanced.\n");
   }
   return 0;
}

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:

Flowchart: Check a parentheses string is balanced or not using stack.


Flowchart: Check a parentheses string is balanced or not using stack.


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.

Go to:


PREV : Stack Sorting Variants.
NEXT : Next Greater/Smaller Element Challenges.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.