Answer to Question #256642 in C for Lucifer

Question #256642

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);


1
Expert's answer
2021-10-26T01:03:25-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS