From 5aab1928a465b34ec2da61179e399a24d004c284 Mon Sep 17 00:00:00 2001 From: Yevhen Kozirovskyi Date: Thu, 31 Oct 2024 23:33:04 +0000 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20a1/program.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- a1/program.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 a1/program.c diff --git a/a1/program.c b/a1/program.c new file mode 100644 index 0000000..73f2b85 --- /dev/null +++ b/a1/program.c @@ -0,0 +1,63 @@ +#include +#include + +#define MAX_LEN 100 + +typedef struct { + char bracket; + int position; +} StackItem; + +int main() { + char line[MAX_LEN + 1]; + StackItem stack[MAX_LEN]; + int top = -1; + + fgets(line, sizeof(line), stdin); + + printf("Read: %s", line); + + for (int i = 0; line[i] != '\0'; i++) { + char ch = line[i]; + + if (ch == '(' || ch == '{' || ch == '[' || ch == '<') { + if (top < MAX_LEN - 1) { + stack[++top].bracket = ch; + stack[top].position = i; + } + } + else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') { + if (top == -1) { + + return 0; + } + + char opening = stack[top].bracket; + int opening_pos = stack[top].position; + top--; + + if ((opening == '(' && ch != ')') || + (opening == '{' && ch != '}') || + (opening == '[' && ch != ']') || + (opening == '<' && ch != '>')) { + char expected; + switch (opening) { + case '(': expected = ')'; break; + case '{': expected = '}'; break; + case '[': expected = ']'; break; + case '<': expected = '>'; break; + } + printf("Crossed bracket %c in %d, expected %c\n", ch, i, expected); + return 0; + } + } + } + + if (top != -1) { + printf("Unmatched opening bracket %c at position %d\n", stack[top].bracket, stack[top].position); + } else { + printf("All brackets OK\n"); + } + + return 0; +}