Advertisement
sylviapsh

Brackets Check

Jan 28th, 2013
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. using System;
  2.  
  3. class AreBracketsCorrect
  4. {
  5.   //Write a program to check if in a given expression the brackets are put correctly.
  6.   //Example of correct expression: ((a+b)/5-d).
  7.   //Example of incorrect expression: )(a+b)).
  8.  
  9.   static void Main()
  10.   {
  11.     Console.WriteLine("Please enter your expression for brackets check:");
  12.     string expression = Console.ReadLine();
  13.  
  14.     int countOpeningBracket = 0,
  15.         countClosingBracket = 0;
  16.     bool isOpened = false;
  17.     int position = 0;
  18.  
  19.     for (int i = 0; i < expression.Length; i++)
  20.     {
  21.       if (expression[i] == '(')
  22.       {
  23.         countOpeningBracket++;
  24.         isOpened = true;
  25.       }
  26.       if (expression[i] == ')' && isOpened == true)//If there is an opened bracket we could count the closed one
  27.       {
  28.         countClosingBracket++;
  29.       }
  30.       else if (expression[i] == ')' && isOpened == false)//Otherwise we exit the cycle because we have found an error
  31.       {
  32.         countOpeningBracket = -1;
  33.         countClosingBracket = -1;
  34.         position = i;
  35.         break;
  36.       }
  37.       if (countOpeningBracket == countClosingBracket) //After each iteration we check if we have closed all open brackets and if so isOpened becomes false
  38.       {
  39.         isOpened = false;
  40.       }
  41.     }
  42.  
  43.     //Print the results
  44.     if (countOpeningBracket == -1 && countClosingBracket == -1)
  45.     {
  46.       Console.WriteLine("Brackets problem encountered! There is a closing bracket that hasn't been opened at position {0}!", position);
  47.     }
  48.     else if (countOpeningBracket == countClosingBracket)
  49.     {
  50.       Console.WriteLine("The brackets in your expression are put correctly!");
  51.     }
  52.     else if (countOpeningBracket > countClosingBracket)
  53.     {
  54.       Console.WriteLine("The number of opening brackets that are not closed is {0}!", countOpeningBracket - countClosingBracket);
  55.     }
  56.     else
  57.     {
  58.       Console.WriteLine("The number of closing brackets that don't have opening ones is {0}!", countClosingBracket - countOpeningBracket);
  59.     }
  60.   }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement