summaryrefslogtreecommitdiffstats
path: root/1/24.c
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-11-23 23:07:52 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-11-23 23:07:52 +0800
commit9027acd597bc3da980d38efaed3383aa57696592 (patch)
tree1291b7fa6d5065dc5c5c59b8d104c83781e2cad0 /1/24.c
parentce26f83b5871a2459e3d607be007cdb6e86b84e7 (diff)
downloadk&r-exercises-9027acd597bc3da980d38efaed3383aa57696592.tar.gz
1.24
Diffstat (limited to '1/24.c')
-rw-r--r--1/24.c66
1 files changed, 66 insertions, 0 deletions
diff --git a/1/24.c b/1/24.c
new file mode 100644
index 0000000..08107e1
--- /dev/null
+++ b/1/24.c
@@ -0,0 +1,66 @@
+#include <stdio.h>
+
+#define MAXLEN 1000
+#define TRUE 1
+#define FALSE 0
+
+#define INLINE 2
+#define MULTILINE 3
+
+/* checks c program for unbalanced parentheses, brackets and braces */
+int main(int argc, char *argv[]) {
+ int p, c, i, comment, quote, parens, bracks, braces;
+
+ p = 0;
+ comment = quote = FALSE;
+ parens = bracks = braces = 0;
+
+ for (i = 0; i < MAXLEN - 1 && (c = getchar()) != EOF; i++) {
+ if (!comment && !quote && (c == '/' || c == '*') && p == '/') {
+ comment = c == '/' ? INLINE : MULTILINE;
+ continue;
+ }
+ if (!comment && !quote && c == '"') {
+ quote = TRUE;
+ continue;
+ }
+ if (comment == INLINE && c == '\n') {
+ comment = FALSE;
+ continue;
+ }
+ if (comment == MULTILINE && c == '/' && p == '*') {
+ comment = FALSE;
+ continue;
+ }
+ if (!comment && quote && c == '"' && p != '\\') {
+ quote = FALSE;
+ continue;
+ }
+ if (!comment && !quote) {
+ if (c == '{')
+ braces++;
+ else if (c == '(')
+ parens++;
+ else if (c == '[')
+ bracks++;
+ else if (c == '}')
+ braces--;
+ else if (c == ')')
+ parens--;
+ else if (c == ']')
+ bracks--;
+ }
+ }
+
+ if (braces != 0)
+ printf("err: input contains %d open braces\n", braces);
+ if (parens != 0)
+ printf("err: input contains %d open parentheses\n", parens);
+ if (bracks != 0)
+ printf("err: input contains %d open brackets\n", bracks);
+
+ if (braces == 0 && parens == 0 && bracks == 0)
+ printf("all braces, parenthese and brackets are balanced!\n");
+
+ return 0;
+} \ No newline at end of file