Sams Teach Yourself C++ in 21 Days

(singke) #1
and think, “two more to do.” You would then add 2+1 and write 3, and think, “one more
to find.” Finally, you would write 3+2 and the answer would be 5. In effect, you are
shifting your attention right one number each time through and decrementing the number
remaining to be found.
Note the condition tested on line 28 (n != 0). Many C++ programmers use the follow-
ing for line 28:
for ( n-=3; n; n-- )
You can see that instead of using a relational condition, just the value of nis used for the
condition in the forstatement. This is a C++ idiom, and nis considered equivalent to n
!= 0. Using just nrelies on the fact that when nreaches 0, it will evaluate false, because
0 has been considered as false in C++. In keeping with the current C++ standards, it is
better to rely on a condition to evaluate to the value of falsethan to use a numeric
value.
Compile, link, and run this program, along with the recursive solution offered on Day 5.
Try finding position 25 and compare the time it takes each program. Recursion is ele-
gant, but because the function call brings a performance overhead, and because it is
called so many times, its performance is noticeably slower than iteration. Microcom-
puters tend to be optimized for the arithmetic operations, so the iterative solution should
be blazingly fast.
Be careful how large a number you enter. fibgrows quickly, and even unsigned long
integers will overflow after a while.

Controlling Flow with switchStatements ..........................................................


On Day 4, you saw how to write ifand if...elsestatements. These can become quite
confusing when nested too deeply, and C++ offers an alternative. Unlike if, which eval-
uates one value,switchstatements enable you to branch on any of several values. The
general form of the switchstatement is
switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}

198 Day 7

Free download pdf