ahamed210

checkbracket1

Sep 21st, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 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.         if(input[i] == '{'){
  14.             stack[top] = '{';
  15.             top++;
  16.         }
  17.         else if(input[i] == '('){
  18.             stack[top] = '(';
  19.             top++;
  20.         }
  21.         else if(input[i] == '['){
  22.             stack[top] = '[';
  23.             top++;
  24.         }
  25.         // Now checking the position is correct or not
  26.  
  27.         else if(input[i] == ']'){
  28.             if(top==0){
  29.                 return 0;
  30.             }
  31.             top--;
  32.             check = stack[top];
  33.             if(check != '['){
  34.                 return 0;
  35.             }
  36.         }
  37.         else if(input[i] == ')'){
  38.             if(top==0){
  39.                 return 0;
  40.             }
  41.             top--;
  42.             check = stack[top];
  43.             if(check != '('){
  44.                 return 0;
  45.             }
  46.         }
  47.         else if(input[i] == '}'){
  48.             if(top==0){
  49.                 return 0;
  50.             }
  51.             top--;
  52.             check = stack[top];
  53.             if(check != '{'){
  54.                 return 0;
  55.             }
  56.         }
  57.     }
  58.     if(top == 0) return 1;
  59.     else return 0;
  60. }
  61. int main()
  62. {
  63.     char input[100];
  64.     scanf(" %[^\n]", input);
  65.  
  66.     if(is_balanced(input)){
  67.         printf("%s is balanced\n", input);
  68.     }
  69.     else{
  70.         printf("%s is not balanced\n", input);
  71.     }
  72.     return 0;
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment