2.4. Another C++ Program: Adding
Integers
Our next program uses the input stream
object std::cin and the stream extraction operator, >>,
to obtain two integers typed by a user at the keyboard, computes the sum of
these values and outputs the result using std::cout. Figure 2.5
shows the program and sample inputs and outputs. Note that we highlight the
user's input in bold.
The comments in lines 1 and 2 state the
name of the file and the purpose of the program. The C++ preprocessor
directive
#include <iostream> // allows program to perform input and output
in line 3 includes the contents of
the <iostream> header file in the program.
The program begins execution with function main
(line 6). The left brace (line 7) marks the beginning of main's body
and the corresponding right brace (line 25) marks the end of main.
Lines 9–11
int number1; // first integer to add
int number2; // second integer to add
int sum; // sum of number1 and number2
are declarations. The
identifiers number1, number2 and sum are the names of
variables. These declarations specify that
the variables number1, number2 and sum are data of
type int, meaning that these
variables will hold integer values, i.e., whole numbers such as 7,–11, 0 and 31914. All
variables must be declared with a name and a data type before they can be used
in a program. Several variables of the same type may be declared in one
declaration or in multiple declarations. We could have declared all three
variables in one declaration as follows:
int number1, number2, sum;
This makes the program less
readable and prevents us from providing comments that describe each variable's
purpose.
We'll soon discuss the data type
double for specifying real numbers, and the data type char for specifying character data. Real numbers are numbers with
decimal points, such as 3.4, 0.0 and–11.19. A char variable may hold only a single lowercase letter, a
single uppercase letter, a single digit or a single special character (e.g.,
$ or *). Types such as int, double and
char are often called fundamental
types or built-in types. Fundamental-type names are keywords and therefore
must appear in all lowercase letters. Appendix
C contains the complete list of fundamental types.
A variable name (such as number1)
is any valid identifier that is not a keyword. An identifier is a series of
characters consisting of letters, digits and underscores (_) that does not begin
with a digit. C++ is case
sensitive—uppercase and lowercase letters are different, so a1
and A1 are different identifiers.
Portability Tip 2.1
|
C++
allows identifiers of any length, but your C++ implementation may impose some
restrictions on the length of identifiers. Use identifiers of 31 characters or
fewer to ensure
portability. |
Good Programming Practice 2.4
|
Avoid
identifiers that begin with underscores and double underscores, because C++
compilers may use names like that for their own purposes internally. This will
prevent names you choose from being confused with names the compilers
choose. |
Error-Prevention Tip 2.1
|
Languages
like C++ are "moving targets." As they evolve, more keywords could be added to
the language. Avoid using "loaded" words like "object" as identifiers. Even
though "object" is not currently a keyword in C++, it could become one;
therefore, future compiling with new compilers could break existing
code. |
Declarations of variables can be placed
almost anywhere in a program, but they must appear before their corresponding
variables are used in the program. For example, in the program of Fig. 2.5, the declaration in line 9
Fig. 2.5. Addition program
that displays the sum of two integers entered at the keyboard.
1 // Fig. 2.5: fig02_05.cpp
2 // Addition program that displays the sum of two integers.
3 #include <iostream> // allows program to perform input and output
4
5 // function main begins program execution
6 int main()
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 std::cout << "Enter first integer: "; // prompt user for data
14 std::cin >> number1; // read first integer from user into number1
15
16 std::cout << "Enter second integer: "; // prompt user for data
17 std::cin >> number2; // read second integer from user into number2
18
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 std::cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24
25 } // end function main
|
Enter first integer: 45
Enter second integer: 72
Sum is 117
|
int number1; // first integer to add
could have been placed
immediately before line 14
std::cin >> number1; // read first integer from user into number1
Line 13
std::cout << "Enter first integer: "; // prompt user for data
prints the string Enter first
integer: on the screen. We like to pronounce the
preceding statement as "std::cout gets
the character string "Enter first integer: "." Line 14
std::cin >> number1; // read first integer from user into number1
uses the input stream
object cin (of namespace
std) and the stream extraction
operator, >>, to obtain a value from the keyboard. Using the stream
extraction operator with std::cin takes character
input from the standard input stream, which is usually the keyboard. We like to
pronounce the preceding statement as, "std::cin gives a value to number1" or simply
"std::cin gives number1."
Error-Prevention Tip 2.2
|
Programs
should validate the correctness of all input values to prevent erroneous
information from affecting a program's
calculations. |
When the computer executes the preceding
statement, it waits for the user to enter a value for variable
number1. The user responds by typing an integer
(as characters), then pressing the Enter key
(sometimes called the Return key) to send the characters to the computer. The
computer converts the character representation of the number to an integer and
assigns (i.e., copies) this number (or value) to the variable number1. Any subsequent references to number1 in this program will use this same value.
Line 16
std::cout << "Enter second integer: "; // prompt user for data
prints Enter second integer: on
the screen, prompting the user to take action. Line 17
std::cin >> number2; // read second integer from user into number2
obtains a value for variable number2 from the
user.
The assignment statement in line 19
sum = number1 + number2; // add the numbers; store result in sum
calculates the sum of the variables number1 and
number2 and assigns the result to variable sum using the assignment operator =. The =
operator and the + operator are called binary operators because each has two operands.
In the case of the + operator, the operands are number1 and
number2. In the case of the preceding = operator, the operands
are sum and the value of the expression number1 + number2.
Line 21
std::cout << "Sum is " << sum << std::endl; // display sum; end line
displays the character string Sum is followed by the
numerical value of variable sum followed by std::endl—a
so-called stream manipulator. The name
endl is an abbreviation for "end line" and belongs to namespace
std. The std::endl stream manipulator
outputs a newline, then "flushes the output buffer." This simply means that, on
some systems where outputs accumulate in the machine until there are enough to
"make it worthwhile" to display them on the screen, std::endl forces any accumulated outputs to be displayed at that
moment. This can be important when the outputs are prompting the user for an
action, such as entering data.
Note that the preceding
statement outputs multiple values of different types. The stream insertion
operator "knows" how to output each type of data. Using multiple stream
insertion operators (<<) in a single statement is referred to as
concatenating, chaining or cascading stream insertion operations. It is unnecessary to have multiple statements to output
multiple pieces of data.
Calculations can also be
performed in output statements. We could have combined the statements in lines
19 and 21 into the statement
std::cout << "Sum is " << number1 + number2 << std::endl;
thus eliminating the need for the
variable sum.
A powerful feature of C++ is that you can create your own data
types called classes (we introduce this capability in Chapter
3 and explore it in depth in Chapters
9 and 10). You can then "teach" C++ how to input and output values of
these new data types using the >> and << operators
(this is called operator overloading—a
topic we explore in Chapter
11).