more review, with some new chapter 3. review c++ simple data types – integral and float –...

Post on 17-Dec-2015

213 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

More Review, with Some New

Chapter 3

Review

• C++ simple data types– Integral and float– Arithmetic operators

• Expressions and expression evaluation– Precedence and associativity of operators

• Assignment statements

New Things - Strings

• C++ strings– #include <string>– String declarations:

• String variables: string myName; • String constant: const string TITLE=“SIR”;• String literals: “Happy Birthday”;

– String size is adjusted to fit what you put in it; e.g.,myName = “George”;myName = myName + “ “ + “Washington”

New Things – Simple I/O

• Assume variable x has been declared (an integer)• Output Statements:

cout << “the answer is: “ << x << endl;cout << x ‘ ‘<< y;

• Input Statements:cin >> x; // read a value into x

• Interactive Input: cout << “Enter an integer value “; cin >> x;

• At this point the system will pause until you type in some value.

Types, Expressions, Assignments

• Type coercion and type casting – what happens if an expression has an integer value but it’s value is assigned to a float (or vice versa)? – Two approaches: coercion & casting– Declarations: float floatX; int intX, intY;

• Coercion: implicit (automatic) conversion of a value from one type to another (Expr. value is coerced to type of left-hand side); for example: floatX=intX+intY;//result converted to float

• If intX and intY are 7 and 31, then floatX = 38.0

Types, Expressions, Assignments

• Casting: explicit conversion, as opposed to automatice.g., instead of someFloat = 3 * someInt; write someFloat = float(3 * someInt);

• The advantage of casting is clarity – everyone knows the conversion is intentional and not inadvertent.

Problems

• Truncation: Causes loss of data when a float is assigned to an int.– Suppose you have these declarations:int x; float y = 5.99;

– Now, x = y;cout << “y is: “<< endl;

will produce this output:y is 5

• In other words, when a float is assigned to an int, the number is truncated to the integer part.

Mixed Type Expressions

• What about expressions whose operands are different types? e.g., 3.5 + 15; 26 % 3 * 3.2; 17/6 + 4.5; 18.5 2*3.2 5 + 4.5 6.2 9.5

• In other words, whenever an operator has two operands of the same type, compute normally (17/6 = 5). Whenever an operator has two operands of different types (float & int, short & int, float & double) convert the shorter form to the longer. In particular if one is an int and one a float, convert the int to a float; for example: 2 * 3.2 is evaluated as 2.0 * 3.2

Function Calls and Library Functions

• A function is a unit of a program• Functions in C++ programs are called (invoked) by

another function (the caller)• When a function is called, control transfers from the

caller to the called function, which executes completely and returns control to the caller.

• Two types of functions in C++– Value returning: returns a single value to caller; invoked from

within an expression– Void: doesn’t directly return a value; is invoked as a separate

statement

Example of Value-Returning#include <iostream>using namespace std;int Square (int);int Cube(int);int main(){

int value 1, value2; // added codevalue1 = 12;value2 = Cube(value1) * 3;cout << “The square of value1 is “ << Square(value1) << endl;cout << “The square of 27 is “ << Square(27) << endl;cout << “and the cube of 27 is “ << Cube(27) << endl;return 0; // return program’s exit status

}

int Square(int n){ return n * n: // return square of input parameter to main}

int Cube(int n){ return n * n * n; // return cube of input parameter to main}• Values computed in the function are used in the expression evaluation

Void Functions

• A void function performs some operation, such as output, or computing a set of values.

• It isn’t used in expressions and it doesn’t directly represent a value, although it can change values in the calling process.getVals(grades, n);A stand-alone statement, might be reading a set of values into an array called grades that has n values.

Library Functionsp. 111

• Libraries contain functions that are used so commonly in programs that it makes sense to collect them into sets and make them available to programmers

• All versions of C++ come with built-in standard libraries. To use one, #include its header file in your program (we’ve already seen this with iostream, for example)

• <cstdlib>: abs(x), labs(longX), for example<cmath> : fabs(x), pow(x, y), sqrt(x), various trig functions, …

<cmath> pow(x, y) arguments: floatsresult type: floatresult value xy

Example: pow(3.5, 2.15) = 3.5 2.15. Restrictions: if x is 0.0, y must be positive

If x < 0.0, y must be a whole number

Actually the arguments are type double, but it’s okay to use floats because of type coercion.

Formatting Output

• Formatting output means that you control how it looks on the screen (or in a file that can be printed).

• For example: tables should be in neat columns with headings

Name Grade Jack 100 Jerry 75 This output is right-justified (lined up according to the last character in each piece of data)

Formatting Basics

• Two endl statements at the end of a line of output will generate a blank line; you can insert spaces in a line by printing blanks:

cout << “the answer is: “ << 13; cout << x << ‘ ‘ << y; //space betw values

• Without added spaces, integer and string values will be output with no space between them.

• Horizontal (within a single line) spacing can also be controlled with manipulators

Manipulators p. 114-115

• Manipulators: functions that are used to format output.

• Manipulators appear in output statements immediately after the insertion operator (<<)

• endl is an example.• Others: setw(n), showpoint, fixed, setprecision(n)

Manipulators

• setw(n) specifies the field width for printing a number; use it to make neat columns. Examples: page 115

• Can be used with string, integer or floating point output• Only applies to the next value that is output• Values are right justified and blank filled if the field is

wider than the number• The field is expanded to the size of the output if the set

width is narrower.• In setting the field width for a floating point number,

allow for the decimal point. In integers or floats allow for a sign.

Manipulators

• fixed is used to print floating point numbers as decimal values, rather than using scientific notation.– e.g., 1400.0 instead of 1.4 x 103 (or, in C/C++ 1.4E3)

• showpoint prints the decimal point if a floating point number has no fractional part. In other words, to prevent values like 87.0 from printing as 87 (by default, floats without a fractional part print as if they are integers.)

• setprecision(n) is also for floating point output. It lets you control the number of digits printed to the right of the decimal point.setprecision(2) prints 12.37890 as 12.38

Manipulators• showpoint, fixed, & setprecision(n) apply to all

output that follows, whereas setw(n) only applies to the next value. (You can turn off any of the first three by repeating the manipulator.)

• Include the header files that define the manipulators. <iostream> for those without parameters, <iomanip> for those with.

• Study examples on page 116, 118 (typos in 1st two) and the table on page 119.

• Don’t try to memorize them exactly; be aware that they exist and remember to look them up and experiment when you write programs. Neatly formatted output is a factor I consider when I grade.

3.8 - String Operations

• Four functions that operate on string data: – length and size (compute the same thing)– find (starting position of a given substring)– substr (return the substring from a given position)

• length: when applied to a string variable returns an unsigned integer that represents the number of characters in the string. Let myName be a string var. Then myName.length()returns its length.

• Note dot notation for calling a function – related to objects• value returning so must be used in an expression; e.g., cout << “my name has “<< myName.length() << “ letters”;

String Functions

• Dot notation is a different way to apply a function to a variable: variable_name.function_name is a type of function call that is used with objects.

• The dot operator connects objects with their methods. myName is an object, and length() is a method (function) that operates on the object. (Object: variable + functions)

• Although the length is typically returned as an unsigned integer, most version of C++ let you assign it to an integer variable.

String Functions• find() (See examples on page 123-124.)

– Is applied to a string variable and– Takes a string as an argument: the argument could be a string literal or a string

variable or a string expression – see example on page 123.– If str1 is of string type, then all the following are legal: str1.find(“the”); str1.find(str2); str1.find(str2 + “abc”)

– The return value of the function is the start position of the string argument, if it is found, or the value string::npos (a system constant, some very large number) if the sub-string can’t be found.

– Technically, the return value is of data type string::size_type but you can probably get by with assigning it to an int variable.

• Be aware that this function exists and understand its purpose but don’t worry about details. The find and substr functions are, in a way, inverses of each other.

String Functions

• The find and substr functions are, in a way, inverses of each other.

• substr(pos, length) (see top of page 125)– pos is the start position, length is the length of the

substring to be returned.– You can assign the substring to a string variable.– If it’s too large (no such position in the string), the function

returns an error.• See the program at the bottom of page 125 and the

table on page 126 for examples of how the functions work.

Summary of Chapter 3

• Numeric types, expressions, output and string operations

• Types should be very familiar to you now.• Expression evaluation, type coercion, casting, and

mixed type assignments are important• Output manipulators: know what they are, refer to

table if you need to.• String operations (functions) & libraries – understand

basic things, look up details if needed.

top related