Problem
Solution
First and for most important thing is that it has to simple. We are not writing a C compiler here. Lets stick to simpleness rather than completeness.
First thing is balancing a brackets,
We could increment counter for every (
and decrement for every )
.
In the end if the count is 0
then the brackets are balanced.
This is not exactly correct (correct implementation would need a stack) but very simple.
Same could be extended to {
, [
.
Every comment /*
should end with */
.
Lets put all these things into C Program.
#include <stdio.h> int main() { int ch = 0, pch = 0; int round_count = 0; int square_count = 0; int flower_count = 0; int comment_count = 0; while((ch = getchar()) != EOF) { if(ch == '(') { round_count++; }else if(ch == '[') { square_count++; }else if(ch == '{') { flower_count++; }else if(ch == '*' && pch == '/') { comment_count++; }else if(ch == ')') { round_count--; }else if(ch == ']') { square_count--; }else if(ch == '}') { flower_count--; }else if(ch == '/' && pch == '*') { comment_count--; } pch = ch; } if(round_count != 0) { printf("Syntax Error: Unbalanced Round brackets\n"); } if(square_count != 0) { printf("Syntax Error: Unbalanced Square brackets\n"); } if(flower_count != 0) { printf("Syntax Error: Unbalanced Flower brackets\n"); } if(comment_count != 0) { printf("Syntax Error: Unbalanced Comment\n"); } return 0; }
Links
- Next Article - K & R : Exercise 2.1 - Range of char, short, int and long
- Previous Article - K & R : Exercise 1.23 - remove C comments
- All Article - K & R Answer
No comments :
Post a Comment