From 40686a542a05eed83998e05a7a1a7eac9e58ff42 Mon Sep 17 00:00:00 2001 From: Marat Izmailov Date: Thu, 24 Oct 2024 10:20:55 +0000 Subject: [PATCH] Add a1/program.c --- a1/program.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 a1/program.c diff --git a/a1/program.c b/a1/program.c new file mode 100644 index 0000000..d8e6e19 --- /dev/null +++ b/a1/program.c @@ -0,0 +1,61 @@ +#include +#include + +#define MAX_LEN 100 + +// Стек для хранения открывающих скобок +char stack[MAX_LEN]; +int top = -1; + +// Функция для добавления элемента в стек +void push(char c) { + if (top < MAX_LEN - 1) { + stack[++top] = c; + } +} + +// Функция для извлечения элемента из стека +char pop() { + if (top >= 0) { + return stack[top--]; + } + return '\0'; // Если стек пустой +} + +// Функция для проверки соответствия скобок +int isMatchingPair(char open, char close) { + return (open == '(' && close == ')') || + (open == '{' && close == '}') || + (open == '[' && close == ']') || + (open == '<' && close == '>'); +} + +int main() { + char code[MAX_LEN]; + printf("Enter the code: "); + fgets(code, MAX_LEN, stdin); + + printf("Read: %s", code); + + for (int i = 0; i < strlen(code); i++) { + char c = code[i]; + + if (c == '(' || c == '{' || c == '[' || c == '<') { + push(c); + } else if (c == ')' || c == '}' || c == ']' || c == '>') { + char lastOpen = pop(); + if (!isMatchingPair(lastOpen, c)) { + printf("Crossed bracket %c in %d, expected %c\n", c, i + 1, lastOpen); + return 1; + } + } + } + + if (top != -1) { + printf("Unclosed bracket %c\n", stack[top]); + return 1; + } + + printf("All brackets OK\n"); + return 0; +}