Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

balanced brackets in c++

#include <iostream>

using namespace std;

int is_balanced(char input[])
{
    char s[100];
    char last;
    int top = 0;
    
    
    for(int i = 0; input[i] != ''; i++)
    {
        if(input[i] == '(' || input[i] == '{' || input[i] == '[')
        {
            s[top] = input[i];
            top++;
        }else if(input[i] == ')' || input[i] == '}' || input[i] == ']')
        {
            if(top == 0)
            {
                return 0;
            }
            
            top--;
            if(s[top] == ')' || s[top] == '}' || s[top] == ']')
            {
                return 0;
            }
        }
    }
    
    if(top == 0)
    {
        return 1;
    }else
    {
        return 0;
    }
    
}

int main()
{
    char input[100];
    cin >> input;
    if(is_balanced(input))
    {
        cout << "Balanced!
";
    }else
    {
        cout << "Imbalanced!
";
    }
    return 0;
}
 
PREVIOUS NEXT
Tagged: #balanced #brackets
ADD COMMENT
Topic
Name
6+2 =