diff --git a/a1/program.c b/a1/program.c new file mode 100644 index 0000000..c8bb8ea --- /dev/null +++ b/a1/program.c @@ -0,0 +1,60 @@ +#include +#include + +#define MAX_LENGTH 100 + +int isMatchingPair(char open, char close) +{ + return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']') || (open == '<' && close == '>'); +} + +int main() +{ + char input[MAX_LENGTH]; + fgets(input, sizeof(input), stdin); + + int len = strlen(input); + if (input[len - 1] == '\n') + { + input[len - 1] = '\0'; + len--; + } + + printf("Read: %s\n", input); + + char stack[MAX_LENGTH]; + + int top = -1; + + for (int i = 0; i < len; i++) + { + char ch = input[i]; + if (ch == '(' || ch == '{' || ch == '[' || ch == '<') + { + stack[++top] = ch; + } + else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') + { + if (top == 0) + { + printf("Crossed bracket %c in %d, expected opening bracket\n", ch, i); + return 0; + } + else if (!isMatchingPair(stack[top], ch)) + { + printf("Crossed bracket %c in %d, expected %c\n", ch, i, (stack[top] == '(' ? ')' : stack[top] == '{' ? '}' : stack[top] == '[' ? ']' : '>')); + return 0; + } + top--; + } + } + + if (top != -1) + { + printf("Unmatched opening bracket %c\n", stack[top]); + return 0; + } + + printf("All brackets OK\n"); + return 0; +} \ No newline at end of file