This Program check in an expression that if the brackets in the expression are in the proper form or not and also it checks for the same no. of opening and closing parenthesis.
This Program takes input from a file named "bracket.txt". Expressions are given there in each new line.Program takes an expression,checks it and shows the result on the display screen.
Code Snipped
- #include<stdio.h>
- #define STACKSIZE 20
- struct stack
- {
- int top;
- char items[STACKSIZE];
- };
- struct stack stk;
- char pop(struct stack *ps)
- {
- char var;
- if(ps->top!=-1)
- {
- var=ps->items[ps->top];
- ps->top--;
- return var;
- }
- }
- void push(struct stack *ps,char a)
- {
- if(ps->top==STACKSIZE-1)
- {
- printf("\nOverflow");
- exit(1);
- }
- else
- {
- ps->top++;
- ps->items[ps->top]=a;
- }
- }
- int main()
- {
- FILE *fp;
- char inp[50],x;
- int i,j,k,dec;
- struct stack *ps;
- ps=&stk;
- fp=fopen("bracket.txt","r");
- if(fp==NULL)
- {
- printf("\nFile Reading Error.\n");
- exit(1);
- }
- while(!feof(fp))
- {
- i=0;j=0;k=0;dec=1;ps->top=-1;
- printf("Expression=");
- fscanf(fp,"%s\n",inp);
- for(k=0;inp[k]!='\0';k++) //printing the expression
- printf("%c",inp[k]);
- while(inp[j]!='\0' && inp[i]!='\0')
- {
- if(inp[j]=='(' || inp[j]=='{' || inp[j]=='[')
- {
- push(ps,inp[j]);
- }
- j++;
- if(inp[i]==')' || inp[i]=='}' || inp[i]==']')
- {
- if(ps->top>-1)
- {
- x=pop(ps);
- if((inp[i]==')' && x=='(') || (inp[i]=='}' && x=='{') || (inp[i]==']' && x=='[')) //Checking the corresponding bracket
- dec=1;
- else
- dec=0;
- }
- else
- dec=0;
- }
- i++;
- if(dec==0)
- break;
- }
- if(dec==0||ps->top>-1)
- printf("\n\tBrackets are not matched.");
- else
- printf("\n\tBrackets are matched.");
- printf("\n\n");
- }
- return 0;
- }
Thanks.
0 Responses to Parenthesis Checking – C Programming and Algorithom