- 2.1 Introduction
- 2.2 First Program in C++: Printing a Line of Text
- 2.3 Modifying Our First C++ Program
- 2.4 Another C++ Program: Adding Integers
- 2.5 Memory Concepts
- 2.6 Arithmetic
- 2.7 Decision Making: Equality and Relational Operators
- 2.8 Wrap-Up
- Summary
- Self-Review Exercises
- Answers to Self-Review Exercises
- Exercises
- Making a Difference
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. In the sample execution, we highlight the user's input in bold.
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 |
The comments in lines 1 and 2 state the name of the file and the purpose of the program. The C++ preprocessor directive in line 3 includes the contents of the <iostream> header. The program begins execution with function main (line 6). The left brace (line 7) begins main's body and the corresponding right brace (line 22) ends it.
Variable Declarations
Lines 9–11
|
are declarations. The identifiers number1, number2 and sum are the names of variables. A variable is a location in the computer's memory where a value can be stored for use by a program. 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 by using a comma-separated list as follows:
|
This makes the program less readable and prevents us from providing comments that describe each variable's purpose.
Fundamental Types
We'll soon discuss the type double for specifying real numbers, and the 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 called fundamental types. Fundamental-type names are keywords and therefore must appear in all lowercase letters. Appendix C contains the complete list of fundamental types.
Identifiers
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.
Placement of Variable Declarations
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
|
could have been placed immediately before line 14
|
the declaration in line 10
|
could have been placed immediately before line 17
|
and the declaration in line 11
|
could have been placed immediately before line 19
|
Obtaining the First Value from the User
Line 13
|
displays Enter first integer: followed by a space. This message is called a prompt because it directs the user to take a specific action. We like to pronounce the preceding statement as "std::cout gets the character string "Enter first integer: "." Line 14
|
uses the standard 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."
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.
The std::cout and std::cin stream objects facilitate interaction between the user and the computer. Because this interaction resembles a dialog, it's often called interactive computing.
Obtaining the Second Value from the User
Line 16
|
prints Enter second integer: on the screen, prompting the user to take action. Line 17
|
obtains a value for variable number2 from the user.
Calculating the Sum of the Values Input by the User
The assignment statement in line 19
|
adds the values of variables number1 and number2 and assigns the result to variable sum using the assignment operator =. The statement is read as, "sum gets the value of number1 + number2." Most calculations are performed in assignment statements. The = operator and the + operator are called binary operators because each has two operands. In the case of the + operator, the two operands are number1 and number2. In the case of the preceding = operator, the two operands are sum and the value of the expression number1 + number2.
Displaying the Result
Line 21
|
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.
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's 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
|
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).