Signup/Sign In

C++ Program to Check for Balanced Bracket String using Stack

Hello Everyone!

In this tutorial, we will learn about the concept of determining whether the input string of brackets is balanced or not using Stack, in the C++ programming language.

To understand the basic functionality of the Stack, we will recommend you to visit the Stack Data Structure, where we have explained this concept in detail from scratch.

For a better understanding of its implementation, refer to the well-commented C++ code given below.

Code:

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

// Returns true is the string is balanced
bool isBalanced(string s)
{
    int i;
    char c;
    int n = s.length();

    stack<char> t;

    for (i = 0; i < n; i++)
    {
        c = s.at(i);

        if (t.empty())
        {
            t.push(c);
        }
        else if (t.top() == '(' && c == ')' || t.top() == '{' && c == '}' || t.top() == '[' && c == ']')
        {
            t.pop();
        }
        else
            t.push(c);
    }

    if (t.empty())
        return true;
    else
        return false;
}

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " ===== Program to determine if the entered string is Balanced using Stack, in CPP  ===== \n\n\n";

    //initializing string to be checked for
    string s1 = "{{[[(())]]}}";
    string s2 = "{[(])}";

    bool b1 = isBalanced(s1);
    bool b2 = isBalanced(s2);

    if (b1)
    {
        cout << "The string " << s1 << " is Balanced.\n\n";
    }
    else
    {
        cout << "The string " << s1 << " is not Balanced.\n\n";
    }

    if (b2)
    {
        cout << "The string " << s2 << " is Balanced.\n\n";
    }
    else
    {
        cout << "The string " << s2 << " is not Balanced.\n\n";
    }

    return 0;
}

Output:

C++ balanced string using Stack

We hope that this post helped you develop a better understanding of the concept of Stack and its implementation to check for balanced bracket string, in CPP. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.