Download presentation
Presentation is loading. Please wait.
Published byRosamond Stevens Modified over 8 years ago
1
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington
2
2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
3
3 C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned
4
4 Standard Data Types in C++ l Integral Types n represent whole numbers and their negatives n No fraction or comma n declared as int, short, or long n 2 bytes, 4 bytes – long n Do not start with 0 - octal l Floating Types n represent real numbers with a decimal point n declared as float – 4 bytes, or double – 8 bytes n Machine dependent n Start with 0 – o.k.
5
5 Samples of C++ Data Values int sample values 4578 -45780 float sample values 95.27495..265 9521E-3-95E-195.213E2 char sample values ‘ B ’ ‘ d ’ ‘ 4 ’‘ ? ’ ‘ * ’
6
6 l Declarations – constants/variables n Constant – start with letter – no quotes n Numeric or alphanumeric n Always use constants instead of literals l Arithmetic Operations n Constants, variables, operators n Unary, binary operators n Modulus - % - only with integers – remainder n Cannot divide by 0 n Same variable on both sides – subtotals n Increment and decrement operators
7
7 Division Operator l the result of the division operator depends on the type of its operands l if one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type l Examples 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75
8
8 Modulus Operator l the modulus operator % can only be used with integer type operands and always has an integer type result l its result is the integer type remainder of an integer division EXAMPLE 11 % 4 has value 3 because ) 4 11 R = ?
9
9 More C++ Operators 8 int age; age = 8; age = age + 1; age 9
10
10 PREFIX FORM Increment Operator 8 int age; age = 8; ++age; age 9
11
11 POSTFIX FORM Increment Operator 8 int age; age = 8; age++; age 9
12
12 Decrement Operator 100 int dogs; dogs = 100; dogs--; dogs 99 dogs
13
13 Operators can be binaryinvolving 2 operands 2 + 3 unaryinvolving 1 operand- 3
14
14 Some C++ Operators Precedence OperatorDescription Higher ( )Function call +Positive - Negative *Multiplication / Division % Modulus (remainder) +Addition - Subtraction Lower = Assignment
15
15 l Precedence Rules n Conversion - promote to more accurate n Type coercion – implicit – forced, automatic n Type casting – explicit - programmer controls n Difference is clarity n Mixed expressions
16
16 Mileage Program /* This program computes miles per gallon given four amounts for gallons used, and starting and ending mileage. Constants: The gallon amounts for four fillups. The starting mileage. The ending mileage. Output (screen) The calculated miles per gallon. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #include using namespace std;
17
17 C++ Code Continued const float AMT1 = 11.7 ; // Number of gallons for fillup 1 const float AMT2 = 14.3 ; // Number of gallons for fillup 2 const float AMT3 = 12.2 ; // Number of gallons for fillup 3 const float AMT4 = 8.5 ; // Number of gallons for fillup 4 const float START_MILES = 67308.0 ; // Starting mileage const float END_MILES = 68750.5 ; // Ending mileage int main( ) { float mpg ; // Computed miles per gallon mpg = (END_MILES - START_MILES) / (AMT1 + AMT2 + AMT3 + AMT4) ;
18
18 Main returns an int value to the operating system cout << “For the gallon amounts “ << endl ; cout << AMT1 << ‘ ‘ << AMT2 << ‘ ‘ << AMT3 << ‘ ‘ << AMT4 << endl ; cout << “and a starting mileage of “ << START_MILES << endl ; cout << “and an ending mileage of “ << END_MILES << endl ; cout << “the mileage per gallon is “ << mpg << endl ; return 0; }
19
19 Variable = Expression l first, Expression on right is evaluated l then the resulting value is stored in the memory location of Variable on left NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable Assignment Operator Syntax
20
20 What value is stored? float a; float b; a = 8.5; b = 9.37; a = b; a b a b 8.5 9.37 ? ?
21
21 What is stored? ? float someFloat; someFloat someFloat = 12; // causes implicit type conversion someFloat 12.0
22
22 What is stored? ? int someInt; someInt someInt = 4.8; // causes implicit type conversion someInt 4
23
23 Type Casting is Explicit Conversion of Type int(4.8) has value4 float(5)has value5.0 float(7/4)has value1.0 float(7) / float(4)has value1.75
24
24 Some Expressions int age; EXAMPLEVALUE age = 8 8 - age- 8 5 + 813 5 / 8 0 6.0 / 5.01.2 float ( 4 / 8 )0.0 float ( 4 ) / 80.5 cout << “How old are you?” cout cin >> agecin cout << agecout
25
25 Functions l every C program must have a function called main l program execution always begins with function main and ends with a ; l Can be called as many times as necessary l any other functions are subprograms and must be called a unique name l Invocation, argument, parameter – allows it to work on different values
26
26 Function Calls l one function calls another by using the name of the called function together with ( ) containing an argument list l a function call temporarily transfers control from the calling function to the called function
27
27 l Value-returning functions – returns one result – not a separate statement l Void functions – procedure – do not return a value – separate statement l Library function – prewritten – don’t forget the header files – hard error to find
28
28 Every C++ function has 2 parts int main ( ) heading { body block return 0; }
29
29 More About Functions l it is not considered good practice for the body block of function main to be long l function calls are used to do tasks
30
30 Where are functions? located in libraries OR written by programmers
31
31 Program with Three Functions #include int Square( int ); // declares these functions int Cube( int ); using namespace std ; int main( ) { cout << “The square of 27 is “ << Square(27) << endl;// function call cout << “The cube of 27 is “ << Cube(27) << endl; // function call return 0; }
32
32 Rest of Program int Square( int n ) // header and body here { return n * n; } int Cube( int n )// header and body here { return n * n * n; }
33
33 Function Call l a function call temporarily transfers control to the called function’s code l when the function’s code has finished executing, control is transferred back to the calling block
34
34 FunctionName = ( Argument List ) The argument list is a way for functions to communicate with each other by passing information. The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function. Function Call Syntax
35
35 A void function call stands alone #include void DisplayMessage ( int n ) ; // declares function int main( ) { DisplayMessage( 15 ) ; //function call cout << “Good Bye“ << endl ; return 0 ; }
36
36 A void function does NOT return a value // header and body here void DisplayMessage ( int n ) { cout << “I have liked math for “ << n << “ years” << endl ; }
37
Two Kinds of Functions Always returns a single value to its caller and is called from within an expression. Never returns a value to its caller, and is called as a separate statement. Value-Returning Void
38
38 Formatting Output l Print or display variables l Insertion operators separate each item l Manipulators – action - l Setw – set width – how many characters in column n Only numbers or strings, not char data n Next data item is right-justified n One-time only action – only applies to following field l Floating-point numbers – decimal is one position n Fixed – force decimal form, not scientific notation n Showpoint – force decimal points to be displayed n Setprecision – control the number of decimal places – rounded off, remains in effect until next setprecision encountered
39
39 << is a binary operator << is called the output or insertion operator << is left associative EXPRESSIONHAS VALUE cout << age cout STATEMENT cout << “You are “ << age << “ years old\n” ;
40
40 is header file l for a library that defines 3 objects an istream object named cin (keyboard) an ostream object named cout (screen) an ostream object named cerr (screen)
41
41 No I/O is built into C++ l instead, a library provides input stream and output stream KeyboardScreen executing program istreamostream
42
42 Manipulators l manipulators are used only in input and output statements l endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format l endl is use to terminate the current output line, and create blank lines in output
43
43 Insertion Operator ( << ) l the insertion operator << takes 2 operands l the left operand is a stream expression, such as cout l the right operand is an expression of simple type, or a string, or a manipulator
44
44 Output Statements SYNTAX (revised) cout << ExpressionOrManipulator << ExpressionOrManipulator... ;
45
45 Output Statements SYNTAX These examples yield the same output. cout << “The answer is “ ; cout << 3 * 4 ; cout << “The answer is “ << 3 * 4 ; cout << Expression << Expression... ;
46
46 Using Manipulators Fixed and Showpoint l use the following statement to specify that (for output sent to the cout stream) decimal format (not scientific notation) be used, and that a decimal point be included (even for floating values with 0 as fractional part) cout << fixed << showpoint ;
47
47 Setprecision(n) l requires #include and appears in an expression using insertion operator (<<) l if fixed has already been specified, argument n determines the number of places displayed after the decimal point for floating point values l remains in effect until explicitly changed by another call to setprecision
48
48 What is exact output? #include // for setw( ) and setprecision( ) #include using namespace std; int main ( ) { float fMyNumber = 123.4587 ; cout << fixed << showpoint ; // use decimal format // print decimal points cout << “Number is ” << setprecision ( 3 ) << fMyNumber << endl ; return 0 ; }
49
49 OUTPUT Number is 123.459 value is rounded if necessary to be displayed with exactly 3 places after the decimal point
50
50 What is exact output? #include // for setw( ) #include using namespace std; int main ( ) { int iMyNumber = 123 ; int iYourNumber = 5 ; cout << setw ( 10 ) << “Mine” << setw ( 10 ) << “Yours” << endl; << setw ( 10 ) << iMyNumber << setw ( 10 ) << iYourNumber << endl ; return 0 ; }
51
51 OUTPUT 12345678901234567890 Mine Yours 123 5 each is displayed right-justified and each is located in a total of 10 positions position
52
52 What is exact output? #include // for setw( ) and setprecision( ) #include using namespace std; int main ( ) { float fMyNumber = 123.4 ; float fYourNumber = 3.14159 ; cout << fixed << showpoint ; // use decimal format // print decimal points cout << “Numbers are: ” << setprecision ( 4 ) << endl << setw ( 10 ) << fMyNumber << endl << setw ( 10 ) << fYourNumber << endl ; return 0 ; }
53
53 OUTPUT Numbers are: 123.4000 3.1416 each is displayed right-justified and rounded if necessary and each is located in a total of 10 positions with 4 places after the decimal point 12345678901234567890
54
54 HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE showpoint none displays decimal point fixed none suppresses scientific notation setprecision(n) int sets precision to n digits setw(n) int sets fieldwidth to n positions endl none terminates output line
55
55 Length Function function length returns an unsigned integer value that equals the number of characters currently in the string function size returns the same value as function length you must use dot notation in the call to function length or size
56
56 find Function function find returns an unsigned integer value that is the beginning position for the first occurrence of a particular substring within the string the substring argument can be a string constant, a string expression, or a char value if the substring was not found, function find returns the special value string::npos
57
57 substr Function function substr returns a particular substring of a string l the first argument is an unsigned integer that specifies a starting position within the string l the second argument is an unsigned integer that specifies the length of the desired substring l positions of characters within a string are numbered starting from 0, not from 1
58
58 What is exact output? #include #include // for functions length, find, substr using namespace std; int main ( ) { string stateName = “Mississippi” ; cout << stateName.length( ) << endl; cout << stateName.find(“is”) << endl; cout << stateName.substr( 0, 4 ) << endl; cout << stateName.substr( 4, 2 ) << endl; cout << stateName.substr( 9, 5 ) << endl; return 0 ; }
59
59 What is exact output? #include #include // for functions length, find, substr using namespace std; int main ( ) { string stateName = “Mississippi” ; cout << stateName.length( ) << endl; // value 11 cout << stateName.find(“is”) << endl;// value 1 cout << stateName.substr( 0, 4 ) << endl;// value “Miss” cout << stateName.substr( 4, 2 ) << endl;// value “is” cout << stateName.substr( 9, 5 ) << endl;// value “pi” return 0 ; }
60
60 Map Measurement Case Study You want a program to determine walking distances between 4 sights in the city. Your city map legend says one inch on the map equals 1/4 mile in the city. You use the measured distances between 4 sights on the map. Display the walking distances (rounded to the nearest tenth) between each of the 4 sights.
61
61 // *************************************************** // Walk program // This program computes the mileage (rounded to nearest // tenth of mile) for each of 4 distances, given map // measurements on map with scale of 1 in = 0.25 mile // *************************************************** #include // for cout, endl #include // For setprecision using namespace std; float RoundToNearestTenth( float ); // declare function const float SCALE = 0.25; // Map scale (mi. per inch) C++ Program
62
62 C++ Code Continued const float DISTANCE1 = 1.5; // First map distance const float DISTANCE2 = 2.3; // Second map distance const float DISTANCE3 = 5.9; // Third map distance const float DISTANCE4 = 4.0; // Fourth map distance int main( ) { float totMiles; // Total of rounded miles float miles;// One rounded mileage cout << fixed << showpoint // Set output format << setprecision(1); totMiles = 0.0;// Initialize total miles
63
63 // Compute miles for each distance on map miles = RoundToNearestTenth( DISTANCE1 * SCALE ); cout << DISTANCE1 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles; miles = RoundToNearestTenth( DISTANCE2 * SCALE ); cout << DISTANCE2 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles;
64
64 // Compute miles for other distances on map miles = RoundToNearestTenth( DISTANCE3 * SCALE ); cout << DISTANCE3 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles; miles = RoundToNearestTenth( DISTANCE4 * SCALE ); cout << DISTANCE4 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles;
65
65 cout << endl << “Total walking mileage is “ << totMiles << “ miles.” << endl; return 0 ;// Successful completion } // *************************************************** float RoundToNearestTenth ( /* in */ float floatValue) // Function returns floatValue rounded to nearest tenth. { return float(int(floatValue * 10.0 + 0.5)) / 10.0; }
66
66 l Define constants n SEVEN = 7 n FOUR = 4 l Display 2 decimal places for each l Display SEVEN / FOUR with integer division l Display SEVEN / FOUR with floating- point division l Display SEVEN / FOUR with floating- point division for both constants l Display SEVEN modulus FOUR
67
67
68
68
69
69 Assignment #5 l Read chapter 4; pg. 151-152 - exam prep questions 1-10, 15-18.
70
70 Assignment #6 l Programming Warm-Up Exercise #8, pg.112 - write out answer - piece of paper, change variable names to correct format; Programming Problem #2, pg. 113 - design, code, output, set up constants for 4 and 7, add output - 7 / 4 using floating-point division for both equals, force result to display 2 decimal places, don't forget header file for manipulators.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.