Parenthesis - C# Programming Exercise

In this exercise, you need to implement a function to check if a sequence of open and closed parentheses is balanced. In other words, the function should check if every open parenthesis corresponds to a closing one and if they are correctly nested.

A parenthesis is correctly nested when each opening parenthesis '(' has a matching closing parenthesis ')', and the pairs close in the right order. In this exercise, you will be given a string containing parentheses, and the function should verify if the sequence is valid or not.

For example:

- The sequence "(()()(()))" is valid because all parentheses are correctly balanced and nested.

- The sequence "(((()" is incorrect because it lacks the closing parenthesis.

This exercise is great for practicing the use of stacks or counters, which are useful data structures for validation and symbol balancing in strings.

 Category

Dynamic Memory Management

 Exercise

Parenthesis

 Objective

Implement a function to check if a sequence of open and closed parentheses is balanced. In other words, check if each open parenthesis corresponds to a closing one and they are correctly nested.

For example:

"(()()(()))" is OK
"(((()" is an ERROR

 Write Your C# Exercise

// Importing necessary namespace for handling collections
using System;  // Basic namespace for console input/output and fundamental operations
using System.Collections.Generic;  // For using the Stack class

class Program
{
    // Function to check if a sequence of parentheses is balanced
    static bool IsBalanced(string parentheses)
    {
        // Create a stack to hold the open parentheses
        Stack stack = new Stack();  // Stack will help to track unmatched open parentheses

        // Iterate through each character in the input string
        foreach (char ch in parentheses)  // For each character in the string
        {
            // If the character is an opening parenthesis, push it onto the stack
            if (ch == '(')  // If the character is an open parenthesis
            {
                stack.Push(ch);  // Add the open parenthesis to the stack
            }
            // If the character is a closing parenthesis, check if there's a matching open parenthesis
            else if (ch == ')')  // If the character is a closing parenthesis
            {
                // If the stack is empty, it means no matching open parenthesis, return false
                if (stack.Count == 0)  // If there are no open parentheses to match with
                {
                    return false;  // It means the parentheses are not balanced
                }
                stack.Pop();  // Remove the top item from the stack (matching the open parenthesis)
            }
        }

        // If the stack is empty, all open parentheses had matching closing parentheses
        return stack.Count == 0;  // If the stack is empty, the parentheses are balanced
    }

    // Main program method to test the IsBalanced function
    static void Main(string[] args)
    {
        // Test the IsBalanced function with valid and invalid examples
        string test1 = "(()()(()))";  // A valid sequence of parentheses
        string test2 = "(((()";  // An invalid sequence of parentheses

        // Display the results of the balance check
        Console.WriteLine($"Is the sequence '{test1}' balanced? {IsBalanced(test1)}");  // Expecting true
        Console.WriteLine($"Is the sequence '{test2}' balanced? {IsBalanced(test2)}");  // Expecting false
    }
}

 Share this C# exercise

 More C# Programming Exercises of Dynamic Memory Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Mix and sort files

    In this exercise, you need to create a program that reads the contents of two different files, merges them, and sorts them alphabetically. The program should be able to take...

  •  ArrayList of Points

    In this exercise, you need to create a structure named "Point3D" to represent a point in 3D space with X, Y, and Z coordinates. The structure should allow storing and manipu...

  •  Search in file

    In this exercise, you need to create a program that reads the contents of a text file, saves the content into an ArrayList, and prompts the user to enter sentences to...

  •  Implementing a queue using array

    In this exercise, you need to implement a queue in C#. A queue is a data structure that follows the FIFO (First In, First Out) principle, meaning the first ele...

  •  Implementing a stack using array

    In this exercise, you need to implement a stack in C#. A stack is a data structure that follows the LIFO (Last In, First Out) principle, meaning the last eleme...

  •  Queue Collections

    In this exercise, you need to create a string queue using the Queue class that already exists in the DotNet platform. The Queue class is an implementation of t...