Lab 3: Experiment 2


Input Expressions

To make it easier to do some of the other experiments, we'll take a look here at input expressions.

Variables Only

Consider this statement:

    cin >> 3;
What do you suppose this would mean? Maybe after this executes, every 3 the program encounters will be replaced with the value the user enters from the keyboard? But this seems quite absurd and perhaps even dangerous. So, a better question: does C++ even allow this? Try it. Add the input statement to your program and recompile.

Question #3.2.1: What is the first compiler error that you get?

Fortunately, C++ doesn't let us do something as undesirable as changing the value of a constant! Instead, all of the objects in an input expression must be variables. So comment out the last incorrect input statement by adding // at the beginning of that line.

Now, let's try this: Add the statement

    cin >> i >> j;
after the declaration of i and j but before the output statement. When you execute your program, enter these values:
    123  456

Question #3.2.2: What values are printed for i and j? Did these values come from their declarations or from your keyboard input?

An input statement replaces the value of a variable used in the input statement. The variable does not remember its old values; that value is gone.

Replacing Values

Now try this variation:

Question #3.2.3: Move the input line before the declaration of i and j. Now what happens?

That's actually a review of the previous lab. Remember that you can't use a variable unless you declare it first. The order of the statements does matter.

Here's a variation that will compile and execute:

Question #3.2.4: Move the input line after the output statement. Whap happens now?

Question #3.2.5: How does this demonstrate that an input statement replaces the values in its variables?

Question #3.2.6: Is it necessary to initialize i and j in their declaration if we read in values for them in the very next statement?

Wrapping Up

NOTE: Be sure to move the input statement back between the declaration and output statements.


Back to the Lab Exercise  |  Forward to the Next Experiment


Report errors to Larry Nyhoff (nyhl@cs.calvin.edu)