QUESTION 11
What must match a closing bracket?
2 marksAnswer
The most recent unmatched opening bracket, with the same bracket type. Merely counting openings and closings is insufficient.
QUESTION 11
The most recent unmatched opening bracket, with the same bracket type. Merely counting openings and closings is insufficient.
QUESTION 12
A bracket-balancing algorithm checks that nested grouping symbols close in the reverse order in which they open.
{[()]} is balanced. ([)] is not: the closing ) arrives while [ is on top. A simple equal-count check would miss that incorrect nesting. An unmatched closing symbol fails immediately, and leftover openings fail at the end.
The last unclosed opening must be the first one closed, which is exactly LIFO order. The stack records both the number and types of pending openings. A counter alone cannot describe every nested type combination.
The example checks grouping symbols in a bounded ordinary line and ignores other characters. It is not a complete C lexer: brackets inside string literals or comments are not specially ignored. State this distinction when applying the algorithm to source-code validation.
A line of n characters is scanned once. Each bracket is pushed or popped once, giving O(n) time. If every character is an opening symbol, the pending stack can contain O(n) symbols. The fixed-size demonstration stack matches its input capacity to avoid overflow.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int read_line(char s[80])
{
if (fgets(s, 80, stdin) == NULL) { return 0; }
char *newline = strchr(s, '\n');
if (newline != NULL) { *newline = '\0'; return 1; }
int ch = getchar();
if (ch == '\n' || ch == EOF) { return 1; }
while ((ch = getchar()) != '\n' && ch != EOF) { }
return 0;
}
int balanced(const char text[])
{
char stack[80]; int top = -1;
for (int i = 0; text[i] != '\0'; ++i) {
char ch = text[i];
if (ch == '(' || ch == '[' || ch == '{') { stack[++top] = ch; }
else if (ch == ')' || ch == ']' || ch == '}') {
if (top < 0) { return 0; }
char opening = stack[top--];
if ((ch == ')' && opening != '(') || (ch == ']' && opening != '[') || (ch == '}' && opening != '{')) { return 0; }
}
}
return top == -1;
}
int main(void)
{
char text[80];
if (!read_line(text)) { puts("Invalid input"); return 1; }
puts(balanced(text) ? "Balanced" : "Unbalanced");
return 0;
}{[()]}Balanced