Balanced Parenthesis in C
×


Balanced Parenthesis in C

222

 Checking for balanced parentheses is a common problem in programming and is often used in compilers, text editors, and many other applications.

 The idea is to ensure that for every opening parenthesis, there is a corresponding closing parenthesis, and they are properly nested.

 One of the most efficient ways to solve this problem is by using a stack data structure.

 The algorithm involves iterating through each character in the input string pushing opening parentheses onto the stack and popping them when a closing parenthesis is encountered.

Example:

Here's a simple C program to check for balanced parentheses using a stack:

// Program for balanced parentheses in C
#include<stdio.h>
#include 

// Structure for stack
typedef struct {
    char items[100];
    int top;
} Stack;

// Initialize stack
void init(Stack *s) {
    s->top = -1;
}

// Push operation
void push(Stack *s, char c) {
    s->items[++s->top] = c;
}

// Pop operation
char pop(Stack *s) {
    if (s->top == -1) {
        return '\0';
    }
    return s->items[s->top--];
}

// Check for balanced parentheses
bool isBalanced(char *st) {
    Stack s;
    init(&s);

    while (*st) {
        if (*st == '(' || *st == '{' || *st == '[') {
            push(&s, *st);
        } else if (*st == ')' || *st == '}' || *st == ']') {
            char popped = pop(&s);
            if ((*st == ')' && popped != '(') ||
                (*st == '}' && popped != '{') ||
                (*st == ']' && popped != '[')) {
                return false;
            }
        }
        st++;
    }

    // Check if stack is empty
    return s.top == -1;
}

// Main function to test the program
int main() {
    char st[100];
    
    printf("Enter a string with parentheses: ");
    scanf("%s", st);

    if (isBalanced(st)) {
        printf("The parentheses are balanced.\n");
    } else {
        printf("The parentheses are not balanced.\n");
    }

    return 0;
}
	
Output:

Enter a string with parentheses:  2 * ( 6 + 5 )2 * ( 6 + 5 )
The parentheses are balanced.

Examples:

Input: ((()))

Output: The parentheses are balanced.

Input: ((){}[])

Output: The parentheses are balanced.

Input: ({[)}

Output: The parentheses are not balanced.

Input: (({})

Output: The parentheses are not balanced.

This program uses a stack to keep track of opening parentheses and checks if each closing parenthesis matches the most recent opening parenthesis.

If the parentheses are balanced, it prints a message saying so; otherwise, it indicates that they are not balanced.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments