Chapter 3 C++(Expressions in interactivity)

Ace your homework & exams now with Quizwiz!

operator precedence

!!

Stream Manipulator - fixed -

Displays floating-point numbers in fixed point notation.

Note!

To use setw, a new header file named iomanip must be added.

Type Casting allows you to perform ________ data type conversion

manual

Integer division

pg99

The ______________ object can be used to read data typed at the keyboard

(cin)

compound operators

+=, -=, *=, /=, %=

Note33

1. The field width of a FP number includes a position for the decimal point. 2. The field width of a string object includes all characters in the string, including spaces. 3. The values printed in the field are right-justified by default. This means they are aligned with the right side of the print field, and any blanks that must be used to pad it are inserted in front of the value.

Mathematical expressions

3.2

Type Conversion:

3.3

Overflow and Underflow

3.4

Type Casting

3.5

Multiple assignment and Combined Assignment

3.6

combined assignment operators

3.6

Formatting output

3.7

The left and right Manipulators -

3.7 continued

Working with charaacters and strings

3.8

3.9

3.9

More Mathematical Library Functions

3.9

stream extraction operator

>>; takes information from a stream and puts it into a variable

keyboard buffer

A small area of memory where keystrokes are stored before they are retrieved into a program.

Type casting cont...

A type cast expression lets you manually promote or demote a value. The general format of a type cast expression is: static_cast<DataType>(value) where Value is a variable or literal value that you wish to convert and DataType is the data type you wish to convert Value to. Here is an example: double number = 3.7; int val; val = static_cast<int>(number); This code defines two variables: number, a double, and val, and int. The type cast expression in the third statement returns a copy of the value in number, converted to an int. When a double is converted to an int, the fractional part is truncated so this statement stores 3 in "val" The original value in number is not changed, however. Type cast expressions are useful in situations where C++ will not perfrm the desired conversion automatically.

Working with characters and string objects

Although it is possible to use cin with the >> operator to input strings, it can cause problems that you need to be aware of. When cin reads input, it passes and ignores any leading whitespace characters (spaces, tabs, or line breaks). Once it comes to the first non-blank character and starts reading, it stops reading when it gets to the next whitespace character.

associativity

An operators associativity is either left to right, or right to left. If two operators sharing an operand have the same precedence, they work according to their associativity

Using cin.get

As with string input, however, there are times when using cin >> to read a character does not do what you want. For example, because it passes over all leading whitespace, it is impossible to input just a blank or {enter} with cin >>. The program will not continue past the cin statement until some character other than the space bar, tab key, or enter key has been pressed. Thus, programs that ask the user to "Press the enter key to continue" cannot use the >> operator to read only the pressing of enter. In those situations, the cin object has a built-in function named (get) that is helpful. Because the get function is built in to the (cin) object, we say that it is a member function of (cin). The get member function reads a single character, including any whitespace character. If the program needs to store the character being read, the get member function can be called in either of the following ways. cin.get(ch) or ch = cin.get(); If the program is using the cin.get function simplyto pause the screen until the enter key is pressed and does not need to store the character, the function can also be called like this: cin.get();

The showpoint Manipulator

By default, FP numbers are not displayed with trailing zeroes, and FP numbers that do not have a fractional part are not displayed with a decimal point. For example double x = 123.4, y = 456.0; cout << setprecision(6) << x << endl; cout << y << endl; The cout statement will produce the following output. 123.4 456

Multiple Assignment and Combined Assignment Continued

C++ allows you to assign a value to multiple variables at once. If a program has several variables, such as a,b,c, and d, and each variable needs to be assigned a value, such as 12, the following statement may be constructed: a = b = c = d = 12; The value of 12 will be assigned to each variable listed in the statement * *The assignment operator works from right to left. 12 is the first assigned to d, then to c, the to b, then to a.

note55

C++ provides several different type cast expressions. static_cast is the most commonly used type cast expression, so we will primarily use it in this book.

string Member Functions and Operators

C++ string objects also have a number of member functions. For example, if you want to know the length of the string that is stored into a string object, you can call the object's length member function. Here is an example of how to use it. string state = "Texas"; int size = state.length(); The first statement creates a string object named state and initializes it with the string "Texas". The second statement defines an int variable named size and initializes it with the length of the string in the state object. After this code executes, the size variable will hold the value 5. Certain operators also work with string objects. One of them is the + operator. You have already encountered the + operator to add two numeric quantities. Because strings cannot be added, when this operator is used with string operands it concatenates them, or joins them together. Assume we have the following defintions and initializations in a program

SM- left

Causes output to be left justified

function - exp - y = exp(x);

Computes the exponential function of the argument, which is x. The return type and the argument are doubles

Stream Manipulator - setw -

Establishes a print field of (n) spaces.

setprecision

FP values may be rounded to a number of significant digits, or precision, which is the total number of digits that appear before and after the decimal point. You can control the number of significant digits with which FP values are displayed by using the setprecision manipulator.

Type Conversion:

If an int is multiplied by a float, what data type will the result be? What is a double is divided by an unsigned int? Is there any way of predicting what will happen in these instances? The answer is yes. C++ follows a set of rules when performing mathematical operations on variables of different data types. It's helpful to understand these rules to prevent subtle errors from creeping into your programs. Just like officers in the military, data types are ranked, One data type outranks another if it can hold a larger number.

The cin object continued

In reality, most programs ask for values that will be assigned to variables. This means the program does not have to be modified if the user wants to run it several times with different sets of data. For example, a program that calculates payroll for a small business might ask the user to enter the name of the employee, the hours worked, and the hourly pay rate. When the paycheck for that employee has been printed, the program could stat over again and ask for the name, hours worked, and hourly pay rate the next employee.

3.8cont..

Inputting a character

Concept:

Multiple assignment means to assign the same value to several variables with one statement.

Combined Assignment operators

Quite often, programs have assignment statements of the following form: number = number +1; The expression on the right side of the assignment operator gives the value of a number plus 1. The result is then assigned to number, replacing the value that was previously stored there. Effectively, this statement adds 1 to number. In similar fashion, the following statement subtracts 5 from number. number = number -5; If you have ever seen this type of statement before, it might cause some initial confusion because the same variable name appears on both sides of the assignment operator.

Random Numbers

Random numbers are useful for lots of different programming tasks. The following are just a few examples: * Random numbers are commonly used in games. For example, computer games that let the player roll dice use random numbers to represent the values on the dice. Programs that show cards being drawn from a shuffled deck use random numbers to represent the face values of the cards. *Random numbers are useful in simulation programs. In some sims, the computer must randomly decide how a person, animal, insect, or other living being will behave. Formulas can be constructed in which a random number is used to determine various actions and events that take place in the program. *Random numbers are useful in statistical programs that must randomly select data for analysis. *Random numbers are commonly used in computer security to encrypt sensitive data

function - abs - y = abs(x);

Returns the absolute value of the argument. The argument and the return value are integers

function - log10 - y = log10(x);

Returns the base-10 logarithm of the argument. The return type and argument are doubles.

function - cos - y = cos(x);

Returns the cosign of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles

function - log - y = log(x);

Returns the natural logarithm of the argument. Return type and argument are doubles

function - sin - y = sin(x);

Returns the sine of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles.

function - sqrt - y = sqrt(x);

Returns the square root of the argument. RT and arg are doubles.

function - tan - y = tan(x);

Returns the tangent of the argument. The angle shoud be expressed in radaians. Doubles again.

function - fmod - y = fmod(x, z);

Returns, as a double, the remainder of the first argument divided by the second argument. Works like the modulus operator, but the arguments are doubles. (The modulus operator only works with integers) Take care not to pass zero at the second argument. Doing so would cause division by zero.

The cin object

So far you have written programs with built-in data. Without giving the user an opportunity to enter his or her own data, you have initialized the variables with the necessary starting values. These types of programs are limited to performing their task with only a single set of starting data. If you decide to change the initial value of any variable, the program must be modified and recompiled.

Inputting a character

Sometimes you want to read only a single character of input. For example, some programs display a menu of items for the user to choose from. Often sections are denoted by the letters A, B, C, and so forth. The use chooses an item from the menu by typing a character. The simplest way to read a single character is with cin and the >> operator-- as below: cin >> ch;

concept:

Special functions exist for working with characters and string objects.

concept:4

The C++ runtime library provides several functions for performing complex mathematical operations.

Using cin.ignore

The cin.ignore function tells the cin object to skip one or more characters in the keyboard buffer. Here is its general from: cin.ignore(n, c); The arguments shown in the parenthesis are optional. If used, n is an integer and c is a character. They tell cin to skip n number of characters, or until the character c is encountered. For example, the following statement causes cin to skip the next 20 characters or until a newline is encountered, whichever comes first: cin.ignore(20,'\n'); If no arguments are used, cin will skip onlythe very next character. Here's an example: cin.ignore();

concept:

The cout object provides ways to format data as it is being displayed. This affects the way data appears on the screen.

Formatting output cont..

The same data can be displayed or printed in several different ways. For example, all of the following numbers have the same value, although they look different: 720 720.0 720.00000000 7.2e+2 +720.0 The way a value is printed is called formatting. The cout object has a standard way of formatting variables of each data type. Sometimes, however, you need more control over the way the data is displayed.

3.7 cont Formatting output

The setprecision Manipulator

A common practice for getting unique seed values is to call the (------) function, which is part of the standard library

Time; This also requires the ctime header file. you pass 0 as the argument.

Overflow and underflow cont..

Trouble can arise when a variable is being assigned to a value that is too large for its type. Here is a statement where a,b, and c are all short integers: a = b * c; If b and c are set to values large enough, the multiplication will produce a number too big to be stored in a. To prepare for this, a should have been defined as an int, or a long int. When a variable is assigned a number that is too large for its data type, it overflows. likewise assigning a value that is too small causes it to underflow.

Type conversion cont...

When C++ is working with an operator, it strives to convert the operands to the same type. This automatic conversion is known as type coercion. When a value is converted to a higher data type is said to be promoted. To demote a value means to convert it to a lower data type.

Cont...

When FP variables overflow and underflow, the results depend upon how the compiler is configured. Your system may produce programs that do any of the following: 1. produces an incorrect result and continues running 2. Prints an error message and immediately stops when either floating point overflow or underflow occurs 3. Prints an error message and immediately stops when floating point overflow occurs, but stores a 0 in the variable when it underflows. 4. Gives you a choice of behaviors when overflow and underflow occurs.

concept2:

When a variable is assigned a value that is too large or too small in range for that variable's data type, the variable overflows or underflows

" Rule 2

When an operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher ranking value In the following expression, assume that years is an int and interestRate is a float: years * interestRate Before the multiplication takes place, years will be promoted to float.

concept:

When an operator's operands are of different data types, C++ will automatically convert them to the same data type. This can affect the results of mathematical expressions.

note3

When sending an expression that consists of an operator to cout, it is always a good idea to put parenthesis around the expression. Some advanced operators will yield unexpected results otherwise.

Rule 3

When the final value of an expression is assigned to a variable, it will be converted to a data type of that variable. n the following statement, assume that area is a long int, while length and width are both ints: area = length * width; Since length and width are both ints, they will not be converted to any other data type. The result of the multiplication, however, will converted to long so it can be stored in (area). Watch out for situations where an expression results in a fractional value being assigned to an integer variable. An example: int x, y = 4; float z =2.7; x = y * z; In the expression y * z, y will be promoted to float and 10.8 will result from the multiplication. Since x is an integer, however, 10.8 will be truncated and 10 will be stored in x.

fixed manipulator

When the fixed manipulator is used, all floating point numbers that are subsequently printed will be displayed with fixed-point notation, with the number of digits to the right of the decimal point specified by the setprecision manipulator. When the fixed and setprecision manipulators are used together, the value specified by the setprecision manipulator will be the number of digits to appear after the decimal point, not the number of significant digits For example: double x = 123.4567; cout << setprecision(2) << fixed << x << endl; Because the fixed manipulator is used, the setprecision maniupulator will cause the number to be displayed as 123.46

Note88

With most compilers, trailing zeroes are displayed when the setprecision and fixed manipulators are used together.

note1

You must include the iostream file in any program that uses cin

to write a fraction for a mathematical equation, in C++, just write with a division symbol in place of the fraction line.

algebraic expression conversion.

SM - showpoint

causes a decimal point and trailing zeroes to be displayed, even if there is no fractional part.

SM- Right

causes output to be right justified.

Rules that govern the evaluation of mathematical expressions: Rule 1

chars, shorts, and unsigned shorts are automatically promoted to int.

____________ is the standard input object.

cin

Do not mix ________-- and cin.get

cin>>

To use the pow function one must include what header file?

cmath

combined assignment operators

combine an arithmetic operator with an assignment operator

arithemetic assignment operators

composed of an arithmetic operator followed by the assignment operator; used to abbreviate an assignment statement that has the following format, in which variableName is the name of the same variable: variableName = variableName arithmeticOperator value

____________ is the standard output object

cout

What header file does the rand function require?

cstdlib

The variable used to store pow's return value should be defined as:

double, so add a decimal and 0 into the tenths location.

The arguments passed, using the pow function and cmath header file, should be what ?

doubles

C++ does not have a ___________ operator

exponent

An ________________ is a programming statement that has a value. usually, an __________ consists of an operator and its operands

expression; expression

Table for operator precedence. The operators on the first row have higher precedence than the ones below

first row: */% second row: + -

Parts of a mathematical expression may be ___________ with ______________________ to force some operations to be perfromed befor others.

grouped with parenthesis.

C++ allows you to construct complex mathematical expressions using multiple operators and __________ _________.

grouping symbols

When you divide an integer by another integer in C++, the result is always an integer. If there is a remainder, it will be discarded. For example, in the following code, parts is assigned the value 2.0: double parts; parts = 15/6; Even though b15 divided by 6 is really 2.5, the .5 part of the result is discarded because we are dividing int and int. It doesn't matter that the" parts" is declared as a double because the fractional part of the result is discarded before the assignment takes place. In order for a division operation to return a floating-point value, at least one of the operands must be a FP data type. For example, the previous code could be written as: double parts; parts = 15.0 / 6; In this code the literal value 15.0 is interpreted as a flaoting-point number, so the division operations will return a FP number. The value 2.5 will be assigned to parts.

integer division

The pow function is useful in operations that involve ____________ exponents.

larger

Yoy can cause values to be either left or right justified by using a ____________ or ____________ manipulator

left or right

In C++, mathematical operations are evaluated from __________ to __________.

left to right; When two operators share an operand, the operator with the highest precedence works first. Multiplication and division have higher precedence than addition and subtraction.

Raising a number to a power requires the use of a _________ ________.

library function; The C++ library isn't a place where you check out books, but a collection of specialized functions. Think of a library function as a "routine" that perfroms a specific operation. One of the library functions is called pow, and its purpose is to raise a number to a power. Here is an example of how it is used: area = pow(4.0, 2.0); This statement contains a call to the pow function. The numbers inside the parentheses are arguments. Arguments are data being sent to the function. The pow function always raises the first argument to the power of the second argument.

Data type ranking list: Highest to lowest (top to bottom)

long double double float unsigned long long unsigned int int

It is possible to build mathematical expressions with several operators. To do this one should consider ____________ ___________.

operator precedence

Your program should always use a cout ____________ before it can read the cin input.

prompt

The C++ library has a function, ------, that you can use to generate random numbers.

rand()

getline function

reads an entire line, including leading and embedded spaces, and stores it in a string object. The getline function looks like the following, where cin is the input stream we are reading from and inputLine is the name of the string object recieving the input getline(cin, inputLine);

SM - setprecision

sets the precision of floating point numbers

You can use ______ to print columns that line up perfectly

setw


Related study sets

CCNA 2 v7 Modules 14 - 16: Routing Concepts and Configuration

View Set

Exam 2: Questions from powerpoints

View Set

1013 Communication (Patient Teaching) Quiz

View Set

Chapter 15 - Sensory Pathways and the Somatic Nervous System

View Set

Photosynthesis/Respiration terms

View Set

Microbial Metabolism Chapter 6: Nester

View Set