0

Please explain!

This is a code based on checking whether the input of an array of parentheses is balanced or not. but i dont undertand a part of the code. Can you plz explain it? what's the function of this part? #include<stdio.h> #include<string.h> int is_balanced(char input[]) { char stack[100], last_char; int top, i, len; top = 0; len = strlen(input); for(i = 0; i < len; i++){ if(input[i] == '(') { stack[top] = '('; top++; } else if (input[i] == ')') { if(top == 0){ /// stack empty return 0; } top--; /******** THIS PART *********/ last_char = stack[top]; if(last_char != '(') { return 0; } /********************************/ } } if(top == 0) return 1; else return 0; } int main() { char input[100]; scanf("%s", input); if (is_balanced(input)) printf("%s is balanced!\n", input); else printf("%s is not balanced!\n", input); return 0; }

26th Dec 2021, 1:45 PM
Swapnil
Swapnil - avatar
1 Answer
+ 2
The author is trying to using a number line of 100 to determine if the numbers of ( and ) are equal. In the part your looking at does an unnecessary check to see if the value in stack[top] is a ( then moves the indices back one. Input (ab) Input[0] goes in stack[0] top goes to 1 Input[3] is ) so the part you looking after the check of the value of top which is currently 1 first moves top to 0 the checks the value of stack[0] to verify it is ( which it is. The since we have reached the end of the loop since top is at 0 the author says the ( and ) are balanced.
26th Dec 2021, 2:33 PM
William Owens
William Owens - avatar