usaa24/a1/program.c

41 lines
914 B
C
Raw Normal View History

2024-10-31 18:45:11 +00:00
#include <stdio.h>
2024-10-31 18:46:23 +00:00
#include <string.h>
2024-10-31 18:45:11 +00:00
int match(char open, char close) {
2024-10-31 18:46:23 +00:00
return (open == '{' && close == '}') || (open == '(' && close == ')');
2024-10-31 18:45:11 +00:00
}
void check_brackets(const char *code) {
char stack[100];
2024-10-31 18:46:23 +00:00
int top = -1;
2024-10-31 18:45:11 +00:00
printf("Read: %s\n", code);
2024-10-31 18:46:23 +00:00
for (int i = 0; code[i] != '\0'; i++) {
2024-10-31 18:45:11 +00:00
char c = code[i];
2024-10-31 18:46:23 +00:00
if (c == '{' || c == '(') {
if (top < 99) {
stack[++top] = c;
}
} else if (c == '}' || c == ')') {
if (top == -1 || !match(stack[top], c)) {
2024-10-31 18:45:11 +00:00
printf("Error at %d\n", i);
return;
}
2024-10-31 18:46:23 +00:00
top--;
2024-10-31 18:45:11 +00:00
}
}
2024-10-31 18:46:23 +00:00
if (top == -1) {
printf("All brackets OK\n");
} else {
printf("Unmatched brackets\n");
}
2024-10-31 18:45:11 +00:00
}
int main() {
char code[100];
printf("Enter code: ");
fgets(code, 100, stdin);
check_brackets(code);
return 0;
2024-10-31 18:46:23 +00:00
}