# #CodeKata-Find Position of parenthesis in a balanced Expression

Problem : Given a balanced expression,find the position of matching parenthesis.

Example :

Given an expression “( ( (  ) ) ) ” and an input which points to an open parenthesis,output the corresponding position of closing parenthesis

If the input is 1  ,the output is 6, because the closing parenthesis for the first open parenthesis closes at position 6.

Solution :

1. Start at the given position of parenthesis and  Initialize a counter with 1.

2.Increment the counter ,when ever you see an open parenthesis.

3. Decrement the counter by 1,when ever you see an closed parenthesis.

4.If the counter is zero,then output the current index which is the match for the open parenthesis .

Code  :

int ReturnClosedParanthesisPosition(string input,int openparenthesisposition)
{
var parenthesisarray = input.ToCharArray();
int counter = 1;
for (int i =openparenthesisposition; i < parenthesisarray.Length; i++)
{
if (parenthesisarray[i]=='(')
{
counter++;
}
if (parenthesisarray[i] == ')')
{
counter--;
}
if (counter == 0)
{
return i;
}
}
return -1;
}