You are currently viewing Easy Code for Checking Parenthesis

Easy Code for Checking Parenthesis

Code for checking Braces placed properly or not

This code is designed for checking braces in an equation. In this code you have to pass an equation in string (character array) format, the code will check whether you have completed or closed braces in proper place or with proper pair. This is the easiest way to implement braces checking concept in C. For Such more codes click here and for video tutorial click here.

#include<stdio.h>
#include<stdlib.h>
#define max 50
typedef struct stack
{
char ar[max];
int top;
}st;

void push(st *,char);
char pop(st *);
char peek(st);
char getmatchsymbol(char);
int isfull(st);
int isempty(st);
int parenthesischeck(char []);

void main()
{
//int ch,g;
char equation[100];
printf("Enter the equation : ");
fgets(equation,100,stdin);

if(parenthesischeck(equation))
printf("Parenthesis are OK");
else
printf("Parenthesis are not OK");
}

void push(st *s,char g)
{
s->ar[++s->top]=g;
}
char  pop(st *s)
{
int p;
p=s->ar[s->top];
s->top--;
return p;
}


char peek(st s)
{
return s.ar[s.top];
}

int isfull(st s)
{
if(s.top==max-1)
return 1;
else
return 0;
}

int isempty(st s)
{
if(s.top==-1)
return 1;
else
return 0;
}

char getmatchsymbol(char ch)
{
    switch(ch)
    {
        case '(': return ')';
        case '{': return '}';
        case '[': return ']';
        case ')': return '(';
        case '}': return '{';
        case ']': return '[';
        
    }
}

int parenthesischeck(char equ[])
{
    int i;
    st s;
    s.top=-1;
    for(i=0;equ[i];i++)
    {
        if(equ[i]=='{' || equ[i]=='(' || equ[i]=='[')
        push(&s,equ[i]);
        else if(equ[i]=='}' || equ[i]==')' || equ[i]==']')
        {
            if(peek(s) == getmatchsymbol(equ[i]))
                pop(&s);
            else
                return 0;
        }
    }
    if(!isempty(s))
        return 0;
    else
        return 1;
}

Leave a Reply