CS333 - Problem Solving and Object Oriented Programming in
C++
[ Home | Schedule
| Personal
Progress | Search | Glossary | Help
]
Missing compound statements can be the source of misunderstanding and therefore errors when writing if/else statements. In the following experiment you will demonstrate several possible errors.
A firm understanding of this problem will help in understanding and avoiding an even more confusing situation caused by nexted if/else statements (see the following experiment for demonstration of those problems).
Consider the following algorithm expressed as pseudocode.
read a number from the standard input if the number is negative then multiple the number by 2 write out a statement that another negative value has been found else multiple the number by 3 write out a statement that another positive value has been found write out the modified number
OK - seems like an easy problem, let's see how many ways it can be screwed up.
EXPERIMENT 1: Since this is simple program, we will
refine it into the C++ code shown below.
#include <iostream.h> void main() { float aNumber; cout << "type in a number: "; cin >> aNumber; if(aNumber < 0) aNumber = aNumber * 2; cout << "You typed in a negative number!\n"; else aNumber = aNumber * 3; cout << "You typed in a positive number!\n"; cout << "The modified number is " << aNumber << endl; }
Hypothesis: What do you think this program will do? Based on your understanding of C++ (which is your current theory of how C++ works), you have a guess (hypothesis) about how this program will behave. To a minute to form your hypothesis.
Experiment: Now try to compile and run this program. (here are two
different ways to run this experiment, On UNIX, On a PC)
What actually did happen? Did it support your hypothesis?
If you were right, then you should have some more confidence in your understanding of C++.
If you were wrong, then you need to fix your understanding of C++.