CS333 - Problem Solving and Object Oriented Programming in C++
[ Home | Schedule | Personal Progress | Search | Glossary | Help ]


Experiment: Missing Compound Statements in if/else construct

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.

rainbow.gif (2251 bytes)

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

rainbow.gif (2251 bytes)

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.

rainbow.gif (2251 bytes)

#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;
}

rainbow.gif (2251 bytes)c++.gif (1085 bytes)

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++.

 

 

What do you think this program will do (hypothesis prior to running the experiment

What result did you observe?

 Did not do this experiment so don't know

For an explanation of what happened and a continuation of this experiment, click submit below


Copyright chris wild 1999.
For problems or questions regarding this website contact [Chris Wild (e-mail:cs333@cs.odu.edu].
Last updated: September 04, 1999.