In-Lab Task 2: Testing if a mathematical expression is balanced or not. Write a function that checks whether parentheses in a mathematical expression are balanced or not. The input to the function will be a pointer to a null-terminated array of characters (string). Assume that all the operands in the expression are single-digit numbers. You should call this function from ‘main’ function to demonstrate that it works as intended. The function should return 0 if the expression is balanced, and the index of mismatch otherwise. The function prototype is given below: int isBalanced(char * ptr_array);
#include <stdio.h>
int isBalanced(char *ptr_array) {
char buffer[1024];
int i = 0;
for (int j = 0; j < sizeof(ptr_array) / sizeof(ptr_array[0]); j++) {
if (i && buffer[i] != ptr_array[j]) {
i--;
} else {
buffer[i++] = ptr_array[i];
}
}
return i;
}
int main() {
char *s = {'(', ')', '(', '(', ')', '(', ')', ')'}
printf("%d", isBalanced(s));
return 0;
}
Comments
Leave a comment