To make it easier to do some of the other experiments, we'll take a look here at input expressions.
Consider this statement:
cin >> 3;What do you suppose this would mean? Maybe after this executes, every
3the 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
// at the beginning of that line.
Now, let's try this: Add the statement
cin >> i >> j;after the declaration of
jbut before the output statement. When you execute your program, enter these values:
Question #3.2.2: What values are printed for
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.
Now try this variation:
Question #3.2.3: Move the input line before the declaration of
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
jin their declaration if we read in values for them in the very next statement?
NOTE: Be sure to move the input statement back between the declaration and output statements.