Sunday, January 15, 2012

C++ Tips and Tricks for Beginners

I am learning a bit of C++ as part of my Engineering curriculum and I am picking up a few interesting tricks along the way and I thought I'd share them with other new learners of C++ hear today. This article is not meant for the pros but you are welcome to read through anyone and I hope you will be kind enough to point out any mistakes I have committed. So here goes:

Tip 1: Use Parenthesis and Logical Operators Whenever in Doubt
It is a rather common mistake to think that the computer is your maths teacher because it can interpret your mathematical expression in an entirely different manner. For example, suppose you want to accept a value and find out if it's between 500 and 1000 (ie. 500<x<1000). But you use a if loop like
The computer will always evaluate it as TRUE. Why? Because it evaluates the function from left to right and because < is a binary operator the evaluation is in fact (500<x)<1000.
Now, 500<x is either 0 (false) or 1 (true) but in either case it is <1000. So the if loop always evaluates as TRUE.

Tip 2: Use Do-While Loop to Your Advantage
The main difference between the do-while loop and other common loops like the for loop or the while loop is that the checking is done at the end of the loop rather than at the beginning. Which means, no matter what the loop will evaluate AT LEAST ONCE. You can use this to your advantage in more ways than you may think and make your program more convenient to write and also create a few nice tricks. Here is a very easy trick you can perform with the while loop:
int main()
define your variables
int rerun;
write your statements
cout<<"Enter 1 to try again"<<endl;

Tip 3: Evaluate Functional Value While Using Non Linear Equation Solving Algorithm
If you are using computer programs for non linear equations solving by methods such as Regula Falsi, Bisection and Newton Ralphston, then keep in mind that the programs have a tendency of returning false roots, ie, values at which the functional value is not sufficiently close zero. So, it is best to CHECK if your functional value is actually zero before returning the answer.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...