Programming tips: Avoiding unbalanced parentheses errors

It’s very common for people to have unbalanced parenthesis after hours of work and hundreds of lines of code.
Also it’s one of the more common questions in exams, find the error/errors in the following code “….” and they give you way too many parentheses.

One of the more popular solutions is to use a pencil and paper to follow the code and see the mistake, but this takes resources and much more time than it should.

The easier and better way is to count. Count what? Count the parentheses.
Any opening/left parenthesis is +1, any closing/right parenthesis is -1. The result should always be 0 and never negative!
So let’s put this into examples.

((a + b) * t / 2 * (1 - t) 
1 1    -1           1    -1 

And we notice that we have 1 remaining, which means the code is wrong.

Next example

(a + b) * t) / (2 * (1 - t)
           ↑
+1   -1    -1

…. wait what? We get -1. If we get -1 the code is 100% wrong.

Good, now the time needed to track and correct parentheses is greatly reduced!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s