In: Computer Science
In C language using stacks:
Activity: Using Stack, check whether the following is
balanced or not : “{ ( ) } ) ”
-Assume a stack of Max_Size = 6
-Draw the stack for each step and show the value of “top”
-If any decision is made (valid/invalid), then write the
reason 11
code:
#include<stdio.h>
char stack[6];//stack of size 6
int top=-1;
void push(char a)
{
stack[++top]=a;
}
char pop()
{
return stack[top--];
}
int main()
{
char str[20],t;
int i,f=1;
//f is flag bit
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='('||str[i]=='{'||str[i]=='[')
push(str[i]);//push for a opening paranthesis
if(str[i]==')'||str[i]=='}'||str[i]==']')//pop for a closing
parenthesis
{
if(top==-1)//check underflow
f=0;
else
{
t=pop();
//ckecking for mismatch of parenthesis
if(str[i]==')'&&(t=='['||t=='{'))
f=0;
if(str[i]=='}'&&(t=='('||t=='['))
f=0;
if(str[i]==']'&&(t=='{'||t=='('))
f=0;
}
}
}
if(top>=0)//unbalanced case
f=0;
if(f==0)
printf("Unbalanced\n");
else
printf("Balanced\n");
return 0;
}
output:
explanation in each step: