2.4 Another C++ Program: Adding Integers

Our next program obtains two integers typed by a user at the keyboard, computes their sum 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. The program begins execution with function main (line 6). The left brace (line 6) begins main’s body and the corresponding right brace (line 21) ends it.

Fig. 2.5 Addition program that displays the sum of two integers.

Alternate View

 1   // Fig. 2.5: fig02_05.cpp
 2   // Addition program that displays the sum of two integers.
 3   #include <iostream> // enables program to perform input and output
 4
 5   // function main begins program execution
 6   int main() {
 7      // declaring and initializing variables
 8      int number1{0}; // first integer to add (initialized to 0)
 9      int number2{0}; // second integer to add (initialized to 0)
10      int sum{0}; // sum of number1 and number2 (initialized to 0)
11
12      std::cout << "Enter first integer: "; // prompt user for data
13      std::cin >> number1; // read first integer from user into number1
14
15      std::cout << "Enter second integer: "; // prompt user for data
16      std::cin >> number2; // read second integer from user into number2
17
18      sum = number1 + number2; // add the numbers; store result in sum
19
20      std::cout << "Sum is " << sum << std::endl; // display sum; end line
21 }    // end function main 

Enter first integer: 45
Enter second integer: 72
Sum is 117

Variable Declarations and List Initialization

Lines 8–10


int number1{0}; // first integer to add (initialized to 0)
int number2{0}; // second integer to add (initialized to 0)
int sum{0}; // sum of number1 and number2 (initialized to 0)

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 (whole number) values, such as 7, –11, 0 and 31914.

Lines 8–10 also initialize each variable to 0 by placing a value in braces ({ and }) immediately following the variable’s name—this is known as list initialization,1 which was introduced in C++11. Previously, these declarations would have been written as:


int number1 = 0; // first integer to add (initialized to 0)
int number2 = 0; // second integer to add (initialized to 0)
int sum = 0; // sum of number1 and number2 (initialized to 0)

Error-Prevention Tip 2.1

Although it’s not always necessary to initialize every variable explicitly, doing so will help you avoid many kinds of problems.

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—for example, we could have declared and initialized all three variables in one declaration by using a comma-separated list as follows:


int number1{0}, number2{0}, sum{0};

This makes the program less readable and prevents us from providing comments that describe each variable’s purpose.

Good Programming Practice 2.4

Declare only one variable in each declaration and provide a comment that explains the variable’s purpose in the program.

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, uppercase letter, digit or special character (e.g., $ or *). Types such as int, double and char are called fundamental types. Fundamental-type names consist of one or more 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.

Portability Tip 2.1

C++ allows identifiers of any length, but your C++ implementation may restrict identifier lengths. Use identifiers of 31 characters or fewer to ensure portability (and readability).

 

Good Programming Practice 2.5

Choosing meaningful identifiers helps make a program self-documenting—a person can understand the program simply by reading it rather than having to refer to program comments or documentation.

 

Good Programming Practice 2.6

Avoid using abbreviations in identifiers. This improves program readability.

 

Good Programming Practice 2.7

Do not use identifiers that begin with underscores and double underscores, because C++ compilers use names like that for their own purposes internally.

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 8


int number1{0}; // first integer to add (initialized to 0)

could have been placed immediately before line 13


std::cin >> number1; // read first integer from user into number1

the declaration in line 9


int number2{0}; // second integer to add (initialized to 0)

could have been placed immediately before line 16


std::cin >> number2; // read second integer from user into number2

and the declaration in line 10


int sum{0}; // sum of number1 and number2 (initialized to 0)

could have been placed immediately before line 18


sum = number1 + number2; // add the numbers; store result in sum

Obtaining the First Value from the User

Line 12


std::cout << "Enter first integer: "; // prompt user for data

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 string "Enter first integer: ".” Line 13


std::cin >> number1; // read first integer from user into number1

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. Pressing Enter also causes the cursor to move to the beginning of the next line on the screen.

Users can, of course, enter invalid data from the keyboard. For example, when your program is expecting the user to enter an integer, the user could enter alphabetic characters, special symbols (like # or @) or a number with a decimal point (like 73.5), among others. In these early programs, we assume that the user enters valid data. As you progress through the book, you’ll learn how to deal with data-entry problems.

Obtaining the Second Value from the User

Line 15


std::cout << "Enter second integer: "; // prompt user for data

prints Enter second integer: on the screen, prompting the user to take action. Line 16


std::cin >> number2; // read second integer from user into number2

obtains a value for variable number2 from the user.

Calculating the Sum of the Values Input by the User

The assignment statement in line 18


sum = number1 + number2; // add the numbers; store result in sum

adds the values of variables number1 and number2 and assigns the result to variable sum using the assignment operator =. We like to read this statement 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.

Good Programming Practice 2.8

Place spaces on either side of a binary operator. This makes the operator stand out and makes the program more readable.

Displaying the Result

Line 20

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.

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.

Calculations can also be performed in output statements. We could have combined the statements in lines 18 and 20 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 discuss this capability in Chapter 3 and explore it in depth in Chapter 9). 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 10).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset