Chapter 3 trial try new oh new 202111example PDF

Title Chapter 3 trial try new oh new 202111example
Course Bacheloroppgave MU
Institution Universitetet i Agder
Pages 50
File Size 5.2 MB
File Type PDF
Total Views 131

Summary

no descrption, about statistic solution and try to read, many summaries and good information to all readers,read as much as you deserve,...


Description

Cengage Learning eBook Print

Page 1 of 50

Printer Friendly Version User Name: Stephen Castleberry email Id: [email protected] Book: A First Book of C++ © 2007 Cengage Learning Inc. All rights reserved. No part of this work may by reproduced or used in any form or by any means - graphic, electronic, or mechanical, or in any other manner - without the written permission of the copyright holder.

Chapter 3 : Assignment and Interactive Input (pp. 79-136) Assignment and Interactive Input: Chapter Objectives

3.1 Assignment Operators 3.2 Formatted Output 3.3 Mathematical Library Functions 3.4 Interactive Keyboard Input 3.5 Symbolic Constants 3.6 Common Programming Errors 3.7 Chapter Summary 3.8 Chapter Supplement: Errors, Testing, and Debugging

Assignment and Interactive Input: Chapter Overview In Chapter 2, you were introduced to the concepts of data storage, variables, and their associated declaration statements. You also saw how the cout object is used to display output data. This chapter continues your introduction to C++ by explaining how data is processed with both assignment statements and mathematical functions. Additionally, it discusses the cin object, which makes it possible for a user to enter data while a program is running. You also learn more about the cout object, which can be used for precise formatting of output data.

3.1 Assignment Operators You learned about simple assignment statements in Chapter 2. An assignment statement is the most basic C++ statement for assigning values to variables and performing computations. This statement has the following syntax:

Cengage Learning eBook Print

Page 2 of 50

P. 79

The simplest expression in C++ is a single constant. In the following assignment statements, the operand to the right of the equals sign is a constant:

In these assignment statements, the value of the constant to the right of the equals sign is assigned to the variable on the left of the equals sign. Note that the equals sign in C++ doesn't have the same meaning as an equals sign in algebra. The equals sign in an assignment statement tells the computer first to determine the value of the operand to its right, and then to store (or assign) this value in the locations associated with the variable on its left. For example, the C++ statement length = 25; formally means “length is assigned the value 25.” The blank spaces in the assignment statement are inserted for readability only. Recall that a variable can be initialized when it's declared. If an initialization isn't done in the declaration statement, the variable should be assigned a value with an assignment statement or input operation before it's used in any computation. Subsequent assignment statements can, of course, be used to change the value assigned to a variable. For example, assume the following statements are executed one after another, and slope wasn't initialized when it was declared:

The first assignment statement assigns the value of 3.7 to the variable named slope.1 The next assignment statement causes the computer to assign a value of 6.28 to slope. The 3.7 that was in slope is overwritten with the new value of 6.28 because a variable can store only one value at a time. Sometimes it's useful to think of the variable to the left of the equals sign as a temporary parking spot in a huge parking lot. Just as a parking spot can be used by only one car at a time, each variable can store only one value at a time. “Parking” a new value in a variable automatically causes the program to remove any value parked there previously. In addition to being a constant, the operand to the right of the equals sign in an assignment statement can be a variable or any other valid C++ expression. An expression is any combination of constants, variables, and function calls that can be evaluated to yield a result. Therefore, the expression in an assignment statement can be used to perform calculations by using the arithmetic operators introduced in Section 2.2. The following are examples of assignment statements using expressions containing these operators:

P. 80

As always in an assignment statement, the program first calculates the value of the expression to the right of the equals sign and then stores this value in the variable to the left of the equals sign. For example, in the assignment statement totalWeight = factor * weight;, the arithmetic expression factor * weight is evaluated first to yield a result. This result, which is a number, is then stored in the variable totalWeight. In writing assignment statements, you must be aware of two important considerations. Because the expression to the right of the equals sign is evaluated first, all variables used in the expression must have been given valid values previously if the result is to make sense. For example, the assignment statement totalWeight = factor * weight; causes a valid number to be stored in totalWeight only if the programmer takes care to assign valid numbers first to both factor and weight. Therefore, the following sequence of statements tells you the values used to obtain the result to be stored in totalWeight:

Cengage Learning eBook Print

Page 3 of 50

Figure 3.1 shows the values stored in the variables factor, weight, and totalWeight.

Figure 3.1 Values stored in variables The second consideration is that because the value of an expression is stored in the variable to the left of the equals sign, only one variable can be listed in this position. For example, this assignment statement is invalid:

The expression on the right evaluates to the integer 1050, which can only be stored in a variable. Because amount + 1892 isn't a valid variable name, the compiler has no means of knowing where to store the calculated value and issues a syntax error message. Program 3.1 shows using assignment statements to calculate the area of a rectangle.

P. 81

Program 3.1

When Program 3.1 is run, this is the output:

Cengage Learning eBook Print

Page 4 of 50

Take a look at the flow of control the computer uses in executing Program 3.1. Program execution begins with the first statement and continues sequentially, statement by statement, until the closing brace of main() is encountered. This flow of control is true for all programs. The computer works on one statement at a time, executing the statement with no knowledge of what the next statement will be. This sequential execution explains why all operands used in an expression must have values assigned to them before the expression is evaluated. When the computer executes the statement area = length * width; in Program 3.1, it uses whatever values are stored in the variables length and width at the time the assignment is executed. If no values have been specifically assigned to these variables before they're used in the expression length * width, the computer uses whatever values happen to occupy these variables when they're referenced. (Most C++ compilers initialize all variables to zero automatically; most also give you a warning that the variable hasn't been explicitly initialized.) The computer doesn't “look ahead” to see whether you assign values to these variables later in the program. It's important to realize that in C++, the equals sign (=) used in assignment statements is an operator, which differs from the way most other high-level languages process this symbol. In C++, the = symbol is called the assignment operator, and an expression using this operator,

P. 82 such as interest = principal * rate, is an assignment expression. Because the assignment operator has a lower precedence than any other arithmetic operator, the value of any expression to the right of the equals sign is evaluated first, before the assignment. Like all expressions, an assignment expression has a value, which is the value assigned to the variable on the left of the assignment operator. For example, the expression a = 5 assigns a value of 5 to the variable a and results in the expression also having a value of 5. The expression's value can always be verified by using a statement such as the following:

This statement displays the expression's value, not the contents of the variable a. Although both the variable's contents and the expression have the same value, you should realize that you're dealing with two distinct entities. From a programming perspective, it's the actual assignment of a value to a variable that's important in an assignment expression; the final value of the assignment expression is of little consequence. However, the fact that assignment expressions have a value has implications that must be considered when you learn about C++'s relational operators in Chapter 4. Any expression terminated by a semicolon becomes a C++ statement. The most common example is the assignment statement, which is simply an assignment expression terminated with a semicolon. For example, terminating the assignment expression a = 33 with a semicolon results in the assignment statement a = 33;, which can be used in a program on a line by itself. Because the equals sign is an operator in C++, multiple assignments are possible in the same expression or in its equivalent statement. For example, in the expression a = b = c = 25, all the assignment operators have the same precedence. The assignment operator has a right-to-left associativity, so the final evaluation proceeds in this sequence:

In this example, this sequence of expressions has the effect of assigning the number 25 to each variable and can be represented as follows:

Appending a semicolon to the original expression results in this multiple assignment statement:

This statement assigns the value 25 to the three variables, equivalent to the following order:

Cengage Learning eBook Print

Page 5 of 50

P. 83

Point of Information: lvalues and rvalues The terms lvalue and rvalue are used often in almost all programming languages that define assignment with an operator that permits multiple assignments in the same statement. An lvalue refers to any quantity that's valid on the left side of an assignment operator, and an rvalue refers to any quantity that's valid on the right side of an assignment operator. For example, each variable you've encountered so far can be an lvalue or rvalue (that is, a variable, by itself, can appear on both sides of an assignment operator), but a number can be only an rvalue. More generally, an expression is an rvalue. Not all variables, however, can be used as lvalues or rvalues. For example, an array type, introduced in Chapter 7, can't be an lvalue or rvalue, but elements in an array can be both.

Coercion When working with assignment statements, keep in mind the data type assigned to the values on both sides of the expression because data type conversions take place across assignment operators. In other words, the value of the expression to the right of the assignment operator is converted to the data type of the variable to the left of the assignment operator. This type of conversion is referred to as a coercion because the value assigned to the variable on the left of the assignment operator is forced into the data type of the variable it's assigned to. An example of a coercion occurs when an integer value is assigned to a real variable; this assignment causes the integer to be converted to a real value. Similarly, assigning a real value to an integer variable forces conversion of the real value to an integer. This conversion always results in losing the fractional part of the number because of truncation. For example, if temp is an integer variable, the assignment temp = 25.89 causes the integer value 25 to be stored in the integer variable temp.2 Another example of data type conversions, which includes both mixed-mode and assignment conversions, is evaluation of the expression

where a and b are integer variables and d is a double-precision variable. When the mixedmode expression b * d is evaluated,3 the value of b used in the expression is converted to a double-precision number for purposes of computation. (Note that the value stored in b remains an integer number, and the resulting value of the expression b * d is a doubleprecision number.) Finally, data type conversion across the assignment operator comes into play. The left side of the assignment operator is an integer variable, so the double-precision value of the expression b * d is truncated to an integer value and stored in the variable a.

P. 84

Assignment Variations Although only one variable is allowed immediately to the left of the equals sign in an assignment expression, the variable to the left of the equals sign can also be used to the right of the equals sign. For example, the assignment expression sum = sum + 10 is valid. Clearly, as an algebraic equation, sum could never be equal to itself plus 10. In C++, however, sum = sum + 10 is not an equation—it's an expression evaluated in two major steps: First, the value of sum + 10 is calculated, and second, the computed value is stored in sum. See whether you can determine the output of Program 3.2.

Program 3.2

Cengage Learning eBook Print

Page 6 of 50

In Program 3.2, the assignment statement sum = 25; tells the computer to store the number 25 in sum, as shown in Figure 3.2.

Figure 3.2 The integer 25 is stored in sum The first cout statement displays the value stored in sum with the message The number stored in sum is 25. The second assignment statement, sum = sum + 10;, causes the program to retrieve the 25 stored in sum and add 10 to this number, yielding 35. The number 35 is then stored in the variable to the left of the equals sign, which is the variable sum. The 25 that was in sum is simply overwritten with the new value of 35 (see Figure 3.3).

P. 85

Figure 3.3 sum = sum + 10; causes a new value to be stored in sum Assignment expressions such as sum = sum + 10, which use the same variable on both sides of the assignment operator, can be written by using the following shortcut assignment operators:

For example, the expression sum = sum + 10 can be written as sum += 10. Similarly, the expression price *= rate is equivalent to the expression price = price * rate. In using shortcut assignment operators, note that the variable to the left of the assignment operator is applied to the complete expression on the right. For example, the expression price *= rate + 1 is equivalent to the expression price = price * (rate + 1), not price = price * rate + 1.

Accumulating Assignment expressions, such as sum += 10 or its equivalent, sum = sum + 10, are common in programming. These expressions are required in accumulating subtotals when data is entered one number at a time. For example, if you want to add the numbers 96, 70, 85, and 60 in calculator fashion, the following statements could be used: Statement Value in sum sum = 0; 0 sum = sum + 96; 96 sum = sum + 70; 166 sum = sum + 85; 251 sum = sum + 60; 311

Cengage Learning eBook Print

Page 7 of 50

The first statement initializes sum to 0, which removes any number stored in sum that would invalidate the final total (a “garbage value”). As each number is added, the value stored in sum is increased accordingly. After completion of the last statement, sum contains the total of all the added numbers. Program 3.3 shows the effect of these statements by displaying sum's contents after each addition.

P. 86

Program 3.3

Program 3.3 displays this output:

Although Program 3.3 isn't a practical program (because adding the numbers by hand is easier), it does illustrate the subtotaling effect of repeated use of statements having this form:

Cengage Learning eBook Print

Page 8 of 50

This type of statement is called anaccumulation statemen. You'll find many uses for accumulation statements when you become more familiar with the repetition statements introduced in Chapter 5.

P. 87

Counting The counting statement, which is an assignment statement similar to the accumulating statement, has the following form:

Examples of counting statements are as follows:

In these examples, the same variable is used on both sides of the equals sign. After the statement is executed, the variable's value is increased by a fixed amount. In the first three examples, the variables i, n, and count have been increased by 1. In the next two examples, the variables have been increased by 2, and in the final example, the variable kk has been increased by 3. For a variable that's increased or decreased by only 1, C++ provides two unary operators: increment and decrement operators. Using the increment operator,4 ++, the expression variable = variable + 1 can be replaced by the expression variable++ or the expression ++variable. Here are examples of the increment operator:

Program 3.4 illustrates the use of the increment operator. It displays the following output:

P. 88

Program 3.4

Cengage Learning eBook Print

Page 9 of 50

When the ++ operator appears before a variable, it's called a prefix increment operator; when it appears after a variable, it's called a postfix increment operator. The distinction between a prefix and postfix increment operator is important when the variable being incremented is used in an assignment expression. For example, k = ++n, which uses a prefix increment operator, does two things in one expression: The value of n is incremented by 1, and then the new value of n is assigned to the variable k. Therefore, the statement k = ++n; is equivalent to these two statements:

The assignment expression k = n++, which uses a postfix increment operator, reverses this procedure. A postfix increment operator works after the assignment is completed. Therefore, the statement k = n++; first assigns the current value of n to k, and then increments the value of n by 1. This process is equivalent to these two statements:

P. 89

C++ also provides the decrement operator, --, in prefix and postfix variations. As you might expect, both the expressions variable-and --variable are equivalent to the expression variable = variable − 1. Here are examples of the decrement operator:

When the -- operator appears before a variable, it's called a prefix decrement operator. When this operator appears after a variable, it's called a postfix decrement operator. For example, both the expressions n-- and --n reduce the value of n by 1 and are equivalent to the longer expression n = n − 1.

Cengage Learning eBook Print

Page 10 of 50

As with the increment operators, however, the prefix and postfix decrement operators produce different results when used in assignment expressions. For example, the expression k = --n first decrements the value of n by 1 before assigning the value of n to k, and the expression k = n-- first assigns the current value of n to k, and then reduces the value of n by 1.

Exercises 3.1

1. (Practice) Write an assignment statement to calculate the circumference of a circle having a radius of 3.3 inches. The formula for determining the circumference, c, of a circle is c = 2πr, where r is the radius and π equals 3.1416. 2. (Practice) Write an assignment statement to calculate the area of a circle. The formula for determining the area, a, of a circle is a = πr2, where r is the radius and π = 3.1416. 3. (Practice) Write an assignment statement to convert temperature in degrees Fahrenheit to degrees Celsius. The formula for this conversion is Celsius = 5.0 / 9.0 (Fahrenheit − 32). 4. (Practice) Write an assignment statement to calculate the round-trip distance, d, in feet, of a trip that's s ...


Similar Free PDFs