Answer to Question #251803 in C for Venice

Question #251803

Two brackets are considered to be a matched pair if the an opening

bracket (i.e., (, [, or { ) occurs to the left of a closing bracket (i.e., ),

], or }) of the exact same type. There are three types of matched

pairs of brackets: [], {}, and (). A matching pair of brackets is not

balanced if the set of brackets it encloses are not matched. WAP to

determine whether the input sequence of brackets is balanced or not.

If a string is balanced, it print YES on a new line; otherwise, print

NO on a new line.

Example: Input: {[()]} and Output: YES

Input: {[(])} and Output: NO


1
Expert's answer
2021-10-15T11:58:16-0400
#include <stdio.h>
#include <string.h>
 
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0 
 


struct Stack {
    int top;
    int array[MAXSIZE];
} stack;
 


void initialize() {
   stack.top = -1;
}


int isFull() {   
    if(stack.top >= MAXSIZE-1)
        return TRUE;
    else
        return FALSE;
}
 


int isEmpty() {
 if(stack.top == -1)
     return TRUE;
 else
     return FALSE;
}
 


void push(int num) {
    if (isFull())
        printf("Stack is Full...\n");
    else {
        stack.array[stack.top + 1] = num;
        stack.top++;
    }
}
 


int pop() {
    if (isEmpty())
        printf("Stack is Empty...\n");
    else {
     stack.top = stack.top - 1;
        return stack.array[stack.top+1];
    }
}
 
int isCorrect(char inputString[100]){
	  int i, length;
	  char  ch;
 length = strlen(inputString);
   
    for(i = 0; i < length; i++){
		if (inputString[i]=='('||inputString[i]=='['||inputString[i]=='{') {  
         push(inputString[i]);
         continue;
      }
      if (isEmpty()==TRUE)    
         return false;
         switch (inputString[i]) {
            case ')':    //for closing parenthesis, pop it and check for braces and square brackets
               ch =pop();
               if (ch=='{' || ch=='[')
                  return FALSE;
                  break;
            case '}': //for closing braces, pop it and check for parenthesis and square brackets
               ch = pop();
               if (ch=='(' || ch=='[')
                  return FALSE;
                  break;
            case ']': //for closing square bracket, pop it and check for braces and parenthesis
               ch = pop();
               if (ch =='(' || ch == '{')
                  return FALSE;
                  break;
         }
    }
	return TRUE;
}


int main() {
    char inputString[100];
  
    initialize();
    printf("Enter a string: ");
    gets(inputString);
   
     
    if(isCorrect(inputString)==TRUE)
        printf("YES\n");
    else
        printf("NO\n");
         


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