Your program should have two variables: one to keep track of left braces, say left_cnt, and the other to keep track of right braces, say right_cnt. Both variables should be initialized to zero. Your program should read and print each character in the input file. The appropriate variable should be incremented each time a brace is encountered. If right_cnt ever exceeds the value of left_cnt, your progra should insert the character pair?? at the point in the output After all the characters in the input file have been proessed, the two variables left_cnt and right_cnt should have the same value. If not, and left_cnt is larger than right_cnt , then a message should be printed that includes the number of right braces missing as a series of the many }'s. For ex:
   ERROR: Missing right braces: }}}

Ans:
   void main( ){
      char x;
      int left_cnt=0,right_cnt=0;
      clrscr( );
      while ((x=getchar())!='\n')
         if(x=='{')
            ++left_cnt;
         else if(x=='}')
            ++right_cnt;
      if(left_cnt==right_cnt)
         printf("\n Braces balanced ");
      else if(left_cnt>right_cnt){
         x=left_cnt - right_cnt;
         printf("\n Error: Missing right braces ");
         while(x--)
            putchar( '}' );
      }
      else{
         x=right_cnt - left_cnt;
         printf("\n Error: Missing left braces ");
         while(x--)
             putchar( '{' );
     }
     getch();
}
   

Categories:

One Response so far.

  1. Troll says:

    Again it's wrong.

    First, getch() is NOT standard C...

    Then you program will say everything is OK if I tell him that:

    }{

    Though it should say something's wrong...

    You should use a stack instead. Push to the stack when "{" and pop when "}". For the rest, I let you think about it...

Leave a Reply