Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class AreBracketsCorrect
- {
- //Write a program to check if in a given expression the brackets are put correctly.
- //Example of correct expression: ((a+b)/5-d).
- //Example of incorrect expression: )(a+b)).
- static void Main()
- {
- Console.WriteLine("Please enter your expression for brackets check:");
- string expression = Console.ReadLine();
- int countOpeningBracket = 0,
- countClosingBracket = 0;
- bool isOpened = false;
- int position = 0;
- for (int i = 0; i < expression.Length; i++)
- {
- if (expression[i] == '(')
- {
- countOpeningBracket++;
- isOpened = true;
- }
- if (expression[i] == ')' && isOpened == true)//If there is an opened bracket we could count the closed one
- {
- countClosingBracket++;
- }
- else if (expression[i] == ')' && isOpened == false)//Otherwise we exit the cycle because we have found an error
- {
- countOpeningBracket = -1;
- countClosingBracket = -1;
- position = i;
- break;
- }
- if (countOpeningBracket == countClosingBracket) //After each iteration we check if we have closed all open brackets and if so isOpened becomes false
- {
- isOpened = false;
- }
- }
- //Print the results
- if (countOpeningBracket == -1 && countClosingBracket == -1)
- {
- Console.WriteLine("Brackets problem encountered! There is a closing bracket that hasn't been opened at position {0}!", position);
- }
- else if (countOpeningBracket == countClosingBracket)
- {
- Console.WriteLine("The brackets in your expression are put correctly!");
- }
- else if (countOpeningBracket > countClosingBracket)
- {
- Console.WriteLine("The number of opening brackets that are not closed is {0}!", countOpeningBracket - countClosingBracket);
- }
- else
- {
- Console.WriteLine("The number of closing brackets that don't have opening ones is {0}!", countClosingBracket - countOpeningBracket);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement