parenthesis amtching program in c programming
March 6, 2023

Parenthesis Matching program in C programming

In this tutorial post, we will write a Parenthesis matching program in a c programming language with practical program code examples and complete a full explanation with the output.


#include<stdio.h>
#include<conio.h>
#define MAXSTK 10

struct stack
{
    int data[MAXSTK];
    int top;
};

int valid_eq(char []);
void push(struct stack *, int );
int pop(struct stack *);

void main()
{
    int flag = 0;
    char eq[20] = "";
    clrscr();
    printf("Enter a Equation:- ");
    gets(eq);
    flag=valid_eq(eq);

    if(flag==1)
        printf("Entered Equation is valid.");
    else
        printf("Entered Equation is not valid.");
    getch();
}

int valid_eq(char eq[])
{
    struct stack s1;
    int i=0;
    char ch;
    s1.top = -1;

    while(eq[i] != '\0')
    {
        if(eq[i] !='\0')
            push(&s1,eq[i]);
        else if(eq[i] == ')')
        {
            if(s1.top == -1)
                return(0);
            else
                ch = pop(&s1);
        }
        i++;
    }
    if(s1.top != -1)
        return(0);
    else
        return(1);
}

void push(struct stack *p, int val)
{
    if(p->top == MAXSTK - 1)
    {
        printf("Stack is Full.");
        return;
    }
    p->top++;
    p->data[p->top] = val;
}

int pop(struct stack *p)
{
    int val;
    if(p->top == -1)
    {
        printf("Stack is Empty.");
        return NULL;
    }

    val = p->data[p->top];
    p->top--;
    return(val);
}