ahamed210

checkbracket

Sep 21st, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. //user defined is_balanced function
  5. int is_balanced(char input[])
  6. {
  7.     char stack[100], check;
  8.     int top, i, length;
  9.     top = 0;
  10.     length = strlen(input);
  11.  
  12.     for(i=0; i<length; i++){
  13.         //taking forward brackets in stack array
  14.         if(input[i] == '('){
  15.             stack[top] = '(';
  16.             top++;
  17.         }
  18.         else if(input[i] == ')'){ //for this brackets there have to be the opposite one in previous position of the stack array
  19.             if(top == 0){
  20.                 return 0;
  21.             }
  22.             top--;
  23.             check = stack[top];
  24.             if(check != '('){
  25.                 return 0;
  26.             }
  27.         }
  28.     }
  29.     if(top == 0) return 1;
  30.     else return 0;
  31. }
  32. int main()
  33. {
  34.     char input[100];
  35.     scanf(" %[^\n]", input);
  36.  
  37.     if(is_balanced(input)){
  38.         printf("%s is balanced\n", input);
  39.     }
  40.     else{
  41.         printf("%s is not balanced\n", input);
  42.     }
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment