Numeric Types, Expressions, and Output 1. Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and.

Slides:



Advertisements
Similar presentations
Dale/Weems/Headington
Advertisements

More Review, with Some New Chapter 3. Review C++ simple data types – Integral and float – Arithmetic operators Expressions and expression evaluation –
Numeric Types, Expressions, and Output ROBERT REAVES.
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
1 Lecture 6: Input/Output (II) Introduction to Computer Science Spring 2006.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
1 Chapter 3 Topics Constants of Type int and float l Evaluating Arithmetic Expressions l Implicit Type Coercion and Explicit Type Conversion l Calling.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
1 Lecture 7 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output
Data Types, Expressions and Functions (part I)
Basic Elements of C++ Chapter 2.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
Due Dates Quiz 1, 2 : Friday September 11 th Quiz 3 : Friday September 18 th Quiz 4 : Monday September 28 th Lab 1, 2 and 3 : Friday Sep 11 th Project.
1 Numeric Types, Expressions, and Output. 2 Chapter 3 Topics  Constants of Type int and float  Evaluating Arithmetic Expressions  Declaration for Numeric.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output CS185/09 - Introduction to Programming Caldwell College.
Numeric Types, Expressions, and Output ROBERT REAVES.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 8: The string Type.
Lecture no 3 Control statements.
1 C++ Syntax and Semantics, and the Program Development Process.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
1 Chapter 3 Numeric Types, Expressions, and Output.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
Chapter 3: Input/Output
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Programming in C++
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
C++ Data Types Check sample values of? ‘4’
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 8: Simple Data Types, Namespaces, and the string Type.
Chapter 3 Numeric Types, Expressions, and Output.
Chapter 3 The New Math. C++ Data Types simple integral charshort intlong bool floating float double Long double enum address pointer reference structured.
CS221 C++ Basics. C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float.
1 A Simple “Hello World” Example #include // input-output library using namespace std; int main() // function main { cout
1 Lecture Three I/O Formatting and Arithmetic Dr. Sherif Mohamed Tawfik.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Chapter 3 Numeric Types, Expressions, and Output
Topic 2 Input/Output.
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Chapter 8: The string Type
Chapter 3: Input/Output
Chapter 3 Input output.
Programming Fundamental-1
Presentation transcript:

Numeric Types, Expressions, and Output 1

Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning Function Using Function Arguments Using C++ Library Functions in Expressions Calling a Void Function C++ Manipulators to Format Output String Operations length, find, and substr 2

3 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

4 C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned

Standard Data Types in C++ Integral Types represent whole numbers and their negatives declared as int, short, or long Floating Types represent real numbers with a decimal point declared as float or double Character Type represents single characters declared as char 5

Samples of C++ Data Values int sample values float sample values E-3-95E E2 char sample values ‘ B ’ ‘ d ’ ‘ 4 ’‘ ? ’ ‘ * ’ 6

7 2.7E4 means 2.7 x 10 4 = = E-4 means 2.7 x = =

More About Floating Point Values Floating point numbers have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing Examples

More About Floating Point Values Alternatively, floating point values can have an exponent, as in scientific notation--the number preceding the letter E doesn’t need to include a decimal point Examples 1.84E1 5E2 8E E3 9

Division Operator The result of the division operator depends on the type of its operands If one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type Examples 11 / 4 has value / 4.0has value / 4.0 has value

11 /******************************************************* FreezeBoil program This program computes the midpoint between the freezing and boiling points of water *******************************************************/ #include using namespace std; const float FREEZE_PT = 32.0; // Freezing point of water const float BOIL_PT = 212.0; // Boiling point of water int main()‏ { float avgTemp; // Holds the result of averaging // FREEZE_PT and BOIL_PT cout << “Water freezes at “ << FREEZE_PT << endl; cout << “ and boils at “ << BOIL_PT << “ degrees.” << endl; avgTemp = FREEZE_PT + BOIL_PT; avgTemp = avgTemp / 2.0; cout << “Halfway between is “; cout << avgTemp << “ degrees.” << endl; return 0; }

12 Function main Continued cout << “Water freezes at “ << FREEZE_PT << endl; cout << “ and boils at “ << BOIL_PT << “ degrees.” << endl; avgTemp = FREEZE_PT + BOIL_PT; avgTemp = avgTemp / 2.0; cout << “Halfway between is “; cout << avgTemp << “ degrees.” << endl; return 0; }

Modulus Operator The modulus operator % can only be used with integer type operands and always has an integer type result Its result is the integer type remainder of an integer division Example: 11 % 4 has value 3 because 13 )‏ R = 3

14 More C++ Operators 8 int age; age = 8; age = age + 1; age 9

15 Prefix Form Increment Operator 8 int age; age = 8; ++age; age 9

16 Postfix Form Increment Operator 8 int age; age = 8; age++; age 9

17 Decrement Operator 100 int dogs; dogs = 100; dogs--; dogs 99 dogs

Which Form to Use When the increment(or decrement) operator is used in a “stand alone” statement solely to add one(or subtract one) from a variable’s value, it can be used in either prefix or postfix form 18 dogs-- ; --dogs; USE EITHER

BUT... When the increment(or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results 19 We’ll see how later...

What is an Expression in C++? An expression is a valid arrangement of variables, constants, and operators In C++ each expression can be evaluated to compute a value of a given type The value of the expression 9.3 * 4.5 is

Operators can be binaryinvolving 2 operands unaryinvolving 1 operand - 3 ternary involving 3 operands later 21

22 Some C++ Operators Precedence OperatorDescription Higher( )Function call +Positive - Negative * Multiplication / Division % Modulus ( remainder) ‏ +Addition - Subtraction Lower = Assignment

Precedence Higher Precedence determines which operator is applied first in an expression having several operators 23

Associativity Left to right associativity means that in an expression having 2 operators with the same priority, the left operator is applied first In C++ the binary operators *, /, %, +, - are all left associative Expression means (9 - 5) – 1 = 3 24

Evaluate the Expression 7 * % 3 * (7 * 10) - 5 % 3 * % 3 * (5 % 3) * * ( 2 * 4) ( )

Parentheses Parentheses can be used to change the usual order Parts in() are evaluated first Evaluate ( 7 *(10 - 5) % 3) * (7 * 5 % 3 ) * ( 35 % 3) * *

Recall Assignment Operator Syntax Variable = Expression First, Expression on right is evaluated 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 27

What value is stored? float a; float b; a = 8.5; b = 9.37; a = b; 28 a b a b ? ?

29 What is stored? ? float someFloat; someFloat someFloat = 12; // Causes implicit type conversion someFloat 12.0

30 What is stored? ? int someInt; someInt someInt = 4.8; // Causes implicit type conversion someInt 4

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 value

Some Expressions int age; ExampleValue age = age / / float(4 / 8)0.0 float(4) /

What values are stored? float loCost; float hiCost; loCost = ; hiCost = ; loCost = float(int(loCost * )) / 100.0; hiCost = float(int(hiCost * )) / 100.0; 33

34 Values were rounded to 2 decimal places hiCost loCost

35 Using Predefined Functions A function (subprogram): set of instructions When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions Predefined functions are organized as a collection of libraries called header files

36 Predefined Functions Header file may contain several functions To use a predefined function, you need the name of the appropriate header file You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do

37 Predefined Function Example To use pow (power), include cmath pow has two numeric parameters The syntax is: pow(x,y) = x y x and y are the arguments or parameters In pow(2,3), the parameters are 2 and 3

HEADER FILE FUNCTION EXAMPLE VALUE OF CALL 38 fabs(x) fabs(-6.4) 6.4 pow(x,y) pow(2.0,3.0) 8.0 sqrt(x) sqrt(100.0) 10.0 log(x) log(2.0) sqrt(x) sqrt(2.0) abs(i) abs(-6) 6

Write C++ Expressions for The square root of b 2 - 4ac sqrt(b * b * a * c) ‏ The square root of the average of myAge and yourAge sqrt((myAge + yourAge) / 2) ‏ 39

Manipulators Manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format endl is use to terminate the current output line and create blank lines in output 40

Using Manipulators Fixed and Showpoint 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; 41

setprecision(n)‏ Requires #include and appears in an expression using insertion operator(<<) If fixed has already been specified, argument n determines the number of places displayed after the decimal point for floating point values Remains in effect until explicitly changed by another call to setprecision 42

43 What is exact output? #include // For setw() and setprecision()‏ #include using namespace std; int main()‏ { float myNumber = ; cout << fixed << showpoint; // Use decimal format // Print decimal points cout << “Number is ” << setprecision(3) << myNumber << endl; return 0; }

44 OUTPUT Number is Value is rounded if necessary to be displayed with exactly 3 places after the decimal point

Manipulator setw “Set width” lets us control how many character positions the next data item should occupy when it is output setw is only for formatting numbers and strings, not char type data 45

setw(n)‏ Requires #include and appears in an expression using insertion operator(<<) Argument n is called the fieldwidth specification, and determines the number of character positions in which to display a right-justified number or string(not char data); the number of positions used is expanded if n is too narrow “Set width” affects only the very next item displayed and is useful to align columns of output 46

47 What is exact output? #include // For setw()‏ #include using namespace std; int main()‏ { int myNumber = 123; int yourNumber = 5; cout << setw(10) << “Mine” << setw(10) << “Yours” << endl << setw(10) << myNumber << setw(10) << yourNumber << endl; return 0; }

48 Output Mine Yours Each is displayed right-justified and each is located in a total of 10 positions position

49 What is exact output? #include // For setw() and setprecision()‏ #include using namespace std; int main()‏ { float myNumber = 123.4; float yourNumber = ; cout << fixed << showpoint; // Use decimal format; print decimal points cout << “Numbers are: ” << setprecision(4)‏ << endl << setw(10) << myNumber << endl << setw(10) << yourNumber << endl; return 0; }

50 OUTPUT Numbers are: 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

51 float x = 312.0; float y = 4.827; cout << fixed << showpoint; OUTPUT cout << setprecision(2) << setw(10) << x << endl ’’’’  3  1  2.00 << setw(10) << y << endl; ’’’’’’  4.83 cout << setprecision(1) << setw(10) << x << endl ’’’’’  3  1  2.0 << setw(10) << y << endl; ’’’’’’’  4.8 cout << setprecision(5) << setw(7) << x << endl 3  1  << setw(7) << y << endl;  More Examples x y 4.827

setfill Used to fill the unused columns with a character other than a space when used with the setw manipulator. cout << setfill(‘*’); cout << setw(5) << 15 << setw(7) << 7634 << setw(8) << “Warm” << endl; Output: ***15***7634****Warm 52

Left and right maniulators Default setting is that output is right justified when using setw. To change to left, use cout << left; Output is then left justified until changed. To change back to right, use cout << right; 53

HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE 54 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 Formatting Output endl manipulator moves output to the beginning of the next line setprecision(n) outputs decimal numbers with up to n decimal places fixed outputs floating-point numbers in a fixed decimal format showpoint forces output to show the decimal point and trailing zeros

56 Types of Manipulators Two types of manipulators: With parameters Without parameters Parameterized: require iomanip header setprecision, setw, and setfill Nonparameterized: require iostream header endl, fixed, showpoint, left, right

57 I/O and the string Type An input stream variable ( cin ) and extraction operator >> can read a string into a variable of the data type string Extraction operator Skips any leading whitespace characters and reading stops at a whitespace character Should not be used to read strings with blanks The function getline Reads until end of the current line Should be used to read strings with blanks getline(cin, mystring);

The string Type To use the data type string, the program must include the header file The statement: string name = "William Jacob"; declares name to be a string variable and also initializes name to "William Jacob" The first character, 'W', in name is in position 0; the second character, 'i', is in position 1, and so on

The string Type (continued)‏ The variable name is capable of storing any size string Binary operator + (to allow the string concatenation operation), and the array subscript operator [], have been defined for the data type string For example, If str1 = "Sunny", the statement stores the string "Sunny Day" into str2 : str2 = str1 + " Day";

length Function Length returns the number of characters currently in the string The syntax to call the length function is: strVar.length()‏ where strVar is variable of the type string length has no arguments length returns an unsigned integer The value returned can be stored in an integer variable

size Function The function size is same as the function length Both functions return the same value The syntax to call the function size is: strVar.size()‏ where strVar is variable of the type string As in the case of the function length, the function size has no arguments

find Function find searches a string for the first occurrence of a particular substring Returns an unsigned integer value of type string::size_type giving the result of the search The syntax to call the function find is: strVar.find(strExp)‏ where strVar is a string variable and strExp is a string expression evaluating to a string The string expression, strExp, can also be a character

find Function (continued)‏ If successful, find returns the position in strVar where the match begins For the search to be successful the match must be exact If unsuccessful, find returns the special value string::npos (“not a position within the string”) ‏

substr Function substr returns a particular substring of a string The syntax to call the function substr is: strVar.substr(expr1,expr2)‏ where expr1 and expr2 are expressions evaluating to unsigned integers

substr Function (continued)‏ The expression expr1 specifies a position within the string (starting position of the substring) ‏ The expression expr2 specifies the length of the substring to be returned

swap Function swap interchanges the contents of two string variables The syntax to use the function swap is strVar1.swap(strVar2); where strVar1 and strVar2 are string variables Suppose you have the following statements: string str1 = "Warm"; string str2 = "Cold"; After str1.swap(str2); executes, the value of str1 is "Cold" and the value of str2 is "War"

String summary A string is a sequence of zero or more characters Strings in C++ are enclosed in double quotation marks The function length returns the number of characters currently in the string The function size returns the number of characters currently in the string The function find searches a string to locate the first occurrence of a particular substring The function substr returns a particular substring of a string The function swap is used to swap the contents of two string variables 70