Parenthesis Learn programming C#

Lesson:

Dynamic Memory Management


Exercise:

Parenthesis 57


Objetive:

Implement a function to check if a sequence of opened and closed parenthesis is balanced, in other words, if each opened parenthesis corresponds to one closed and they are also well nested.

For example:

(()()(())) OK
(((() ERROR


Code:

using System;
using System.Collections;
namespace Expression
{
    class Program
    {
        static void Main(string[] args)
        {
            string expresion = "()()()()()()";
            bool expresionMal = false;

            Stack pila = new Stack();

            for (int i = 0; i < expresion.Length; i++)
            {
                if (expresion[i] == '(')
                    pila.Push(expresion[i]);
                else if (expresion[i] == ')')
                    if (pila.Count > 0)
                        pila.Pop();
                    else
                        expresionMal = true;
            }

            if (expresionMal)
                Console.WriteLine("ERROR");
            else
                Console.WriteLine("OK");

            Console.ReadLine();
        }
    }
}