Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
static int Control(int x=0)

     {
         string str = "(a(b(c)d)e)";

         for (int i = 0; i <= str.Length; i++)
         {
             if (str[i] =='(')

                 x++;

             if (str[i] == ')')
                 x--;
         }
         return x;

     }

     static void Main(string[] args)
     {
         int x = 0;

         bool flag = false;
         if (Control(x)==0)

         {
             flag = true;
         }
         Console.WriteLine(flag);

         Console.ReadLine();
     }
Posted
Updated 6-Jan-13 7:54am
v2
Comments
Wendelius 6-Jan-13 13:54pm    
What's the return value and what would you think it should be?

Also have you tried yet creating the recursive version?
Wendelius 6-Jan-13 14:10pm    
Also try using the debugger to see what actually happens. You can also try a bit different string. What happens with:

...
string str = "(a(b(cde)";
...

1 solution

You were ordered to write two functions, but you have written only one, incorrectly. Also, you did not explain your question properly.

From the very beginning: we are not going to do your homework for your. You are given a change to solve your assignments to learn something. Use this chance well.

Now, in your code there I can see two bugs. First, instead of '<=' you should use '<', in the ending condition of the loop. In the last element, you will get out-of-range exception; there are no elements at the index of [str.Length] or above.

The second one is the function signature. You don't need x as a parameter. Declare it locally.

One important practical advice: never ever create single-character names of any entities. How are you going to use "Find" functionality? How can you figure out what do they mean if you read your own code later? All the names should be semantic, maybe, not too long, but self-explaining and even without use of abbreviation: instead of "i" — "index"; instead of "x" — "count", or "balance".

Good luck with recursion version and everything else.

—SA
 
Share this answer
 
Comments
ridoy 6-Jan-13 15:14pm    
+5
Sergey Alexandrovich Kryukov 6-Jan-13 19:14pm    
Thank you,
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900