Operations and Expressions Chapter 3. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further work with Object-Centered Design Detailed look at.

Slides:



Advertisements
Similar presentations
Chapter 2 Part B CISS 241. Take a few moments and work with another student to develop an algorithm for a program that will add two whole numbers (integers)
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
True or false A variable of type char can hold the value 301. ( F )
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Operations and Expressions Chapter 3. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further work with Object-Centered Design Detailed look at.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Data types and variables
Operations and Expressions. Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of.
Chapter 2: Introduction to C++.
JavaScript, Third Edition
Data Types, Expressions and Functions (part I)
Basic Elements of C++ Chapter 2.
CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will:  Become familiar with the basic components of a C++ program, including functions, special.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Expressions, Data Conversion, and Input
Objectives You should be able to describe: Data Types
Operaciones y Variables
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Operations Making Things Happen. Our Scuba Program #include // cin, cout, > using namespace std; int main() { const double FEET_PER_ATM = 33.0, LBS_PER_SQ_IN_PER_ATM.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2: Using Data.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
PROCESSING Numeric Types. Objectives Be able to … Explain the difference between a literal, a variable and a constant Declare numeric variables and constants.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
CPS120: Introduction to Computer Science Operations Lecture 9.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2.
1 Operations Making Things Happen (Chap. 3) Expressions.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
A FIRST BOOK OF C++ CHAPTER 3 ASSIGNMENT AND INTERACTIVE INPUT.
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.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Operations Chapter 4 & Section Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Programming Fundamentals. Summary of Previous Lectures Phases of C++ Environment Data Types cin and cout.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Bill Tucker Austin Community College COSC 1315
Operations Making Things Happen.
Today Variable declaration Mathematical Operators Input and Output Lab
Chapter Topics The Basics of a C++ Program Data Types
Completing the Problem-Solving Process
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Copyright © 2012 Pearson Education, Inc.
Basic Elements of C++ Chapter 2.
Operators and Expressions
Lecture 3 Expressions Richard Gesick.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Chapter 2: Introduction to C++.
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
C++ for Engineers and Scientists Second Edition
Presentation transcript:

Operations and Expressions Chapter 3

C++ An Introduction to Computing, 3rd ed. 2 Objectives Further work with Object-Centered Design Detailed look at numeric types Work with bool expressions Consider the processing of characters Study assignment operator Use increment, decrement operators First look at class constructors

C++ An Introduction to Computing, 3rd ed. 3 Expressions Definition: any sequence of objects and operations that combine to produce a value (of a type) is called an expression. Example: double pressure = ((depth / FEET_PER_ATM) + 1) * LBS_PER_SQ_IN_PER_ATM;

C++ An Introduction to Computing, 3rd ed. 4 Numeric Expressions C++ provides four familiar arithmetic operators: + for performing addition - for performing subtraction * for performing multiplication / for performing division Each of these four can be applied to either real ( double ) or integer ( int ) operands (Literal, variable, constant, expression etc).

C++ An Introduction to Computing, 3rd ed. 5 Division Division behaves differently for int and double operands Note the results of the following 3/4  03.0/4.0  /4  0.753/4.0  0.75 If both operands are integers Integer division performed Otherwise real division performed

C++ An Introduction to Computing, 3rd ed. 6 Integer vs. Real Division Recall division from grade school. Teacher: “4 goes into 3 how many times?” Pupils: “0 times with a remainder 4” The expression 3 / 4 returns the quotient. This is integer division The expression 3 % 4 returns the remainder (how about 3%(-4) ?). This is read, "3 mod 4"

C++ An Introduction to Computing, 3rd ed. 7 Type Conversions Combining an int and a real in the same expression  5.0 C++ automatically converts narrow values into wider values An integer is converted to a real Result of the expression is a real Often called "promotion"

C++ An Introduction to Computing, 3rd ed. 8 Precedence Consider the possible value of the expression * 4 (2 + 3) * 4  24 or 2 + (3 * 4)  14 ? Operator precedence governs evaluation order. * has higher precedence than + * is applied first (when ‘(‘ and ‘)’ are not involved)

C++ An Introduction to Computing, 3rd ed. 9 Operator Precedence (), (), [],., -> (left) HIGHER +, -,!(NOT) unary (right) *, /, %binary(left) +,-, >= ==, != && || LOWER See Appendix C for a complete list...

C++ An Introduction to Computing, 3rd ed. 10 Associativity Consider the possible value of the expression (8 - 4) - 2  4 or 8 - (4 - 2)  6 ? Precedence doesn’t help us Associativity tells us. Subtraction is left-associative, the left - is evaluated first, giving us 4. Most (but not all) C++ operators associate left. See Appendix C in the text for a complete list...

C++ An Introduction to Computing, 3rd ed. 11 Numeric Functions The library contains a variety of mathematical functions, including: sin(x) asin(x) cos(x) acos(x) tan(x) atan(x) sqrt(x) log10(x) log(x) pow(x, y) floor(x) ceiling(x) abs(x)

C++ An Introduction to Computing, 3rd ed. 12 Using functions #include using namespace std; int main() { cout << “\nEnter base and exponent: “; double base, exponent; cin >> base >> exponent; double result = pow(base, exponent); cout << base << “ raised to the power “ << exponent << “ is “ << result << endl; }

C++ An Introduction to Computing, 3rd ed. 13 Type Conversions Possible to explicitly convert a value from one type to another Syntax to use: type (expression) or (type) expression Conversion can cause loss of data double x = 3.456; cout << (int) x; What gets output? 3

C++ An Introduction to Computing, 3rd ed. 14 Boolean Expressions C++ type bool has two literals false and true Relational operators produce boolean expressions (char, integer, real)

C++ An Introduction to Computing, 3rd ed. 15 Relational Operations Use operators for comparisons Each takes two operands Produces a bool value ( true or false ): x == y x != y x = y x > y x <= y Warning: Do NOT confuse = (assignment) With == (equality). 3<x<6 is NO GOOD

C++ An Introduction to Computing, 3rd ed. 16 Compound Boolean Expressions Logical operators

C++ An Introduction to Computing, 3rd ed. 17 Compound Boolean Expressions More complex boolean expressions can be built using the logical operators: a && b // true iff a, b are both true a || b // true iff a or b is true !a // true iff a is false Example: cin >> score; assert (0 <= score && score <= 100);

C++ An Introduction to Computing, 3rd ed. 18 Short-Circuit Evaluation Consider the boolean expression ( n != 0 ) && ( x < 1.0 / n ) If n == 0 the right hand expression causes a program crash C++ will evaluate the original expression from left to right If n == 0, the left expression evaluates false Since it is an &&, this makes the whole expression false Thus it does not proceed to the right expression

C++ An Introduction to Computing, 3rd ed. 19 Preconditions Definition: When a program makes assumptions about its input values Example: that they’re positive Preconditions are boolean expressions Must be true in order for the program to work correctly. To check preconditions, C++ provides the assert() mechanism...

C++ An Introduction to Computing, 3rd ed. 20 Assertions #include using namespace std; int main() { cout << “\nEnter your age: “; int age; cin >> age; assert(age > 0); //... } Required to use the assert command assert() will halt the program if age <= 0

C++ An Introduction to Computing, 3rd ed. 21 Character Expressions Character variables can be … Declared and initialized char middleInitial = 'Q'; Assigned middleInitial = 'Z'; Used for I/O cout << middleInitial; cin >> middleInitial; Compared assert (middleInitial != 'X');

C++ An Introduction to Computing, 3rd ed. 22 Character Functions Boolean character-processing functions found in library: isalpha(ch) isalnum(ch) isdigit(ch) iscntrl(ch) islower(ch) isupper(ch) isspace(ch) ispunct(ch) isprint(ch) isgraph(ch) Case-conversion functions: toupper(ch) tolower(ch)

C++ An Introduction to Computing, 3rd ed. 23 Assignment expression vs statement Syntax: variable = expression (;) Expression is evaluated Value placed in memory location associated with variable Note: Left side must be a variable, and the type of the right side must compatible to the variable’s type Example: xCoord = 4.56; code = 'T';

C++ An Introduction to Computing, 3rd ed. 24 Assignment Given the sequence of three assignment statements, note the results Note that previous variable values are gone after execution of assignment

C++ An Introduction to Computing, 3rd ed. 25 Assignment The assignment operator = Right-associative, Supports expressions like: int w, x, y, z; w = x = y = z = 0; The rightmost = is applied first, assigning z zero, then y is assigned the value of z (0), then x is assigned the value of y (0) finally w is assigned the value of x (0).

C++ An Introduction to Computing, 3rd ed. 26 Assignment Shortcuts Some assignments are so common: var = var + x; // add x to var var = var - y; // sub y from var C++ provides shortcuts for them: var += x; // add x to var var -= y; // sub y from var

C++ An Introduction to Computing, 3rd ed. 27 In General Most arithmetic expressions of the form: var = var  value; can be written in the “shortcut” form: var  = value; Examples: double x, y; cin >> x >> y; x *= 2.0; // double x’s value y /= 2.0; // decrease y by half

C++ An Introduction to Computing, 3rd ed. 28 Increment and Decrement Other common assignments include: var = var + 1; // add 1 to var var = var - 1; // sub 1 from var C++ provides shortcuts for them, too: var++; // add 1 to var var -- ; // sub 1 from var

C++ An Introduction to Computing, 3rd ed. 29 Prefix Increment The prefix form of increment produces the final (incremented) value as its result: int x, y = 0; x = ++y; cout << x; // 1 is displayed The prefix decrement behaves similarly...

C++ An Introduction to Computing, 3rd ed. 30 Postfix Increment The postfix form of increment produces the original (unincremented) value as its result: int x, y = 0; x = y++; cout << x; // 0 is displayed // y now holds value of 1 The prefix decrement behaves similarly...

C++ An Introduction to Computing, 3rd ed. 31 Prefix vs. Postfix So long as the increment (or decrement) operator is used as a separate statement: int y = 0, x = 0; ++x; // x == 1 y++; // y == 1 … it makes no difference which version is used.

C++ An Introduction to Computing, 3rd ed. 32 Expressions into Statements – Semicolons An expression followed by a semicolon becomes an expression statement x = y + z; 'A'; cos (z); All are expression statements This expression statement has the added side effect of changing the value of x

C++ An Introduction to Computing, 3rd ed. 33 I/O Streams C++ has no I/O as part of the language I/O streams are provided by istream and ostream cout cin

C++ An Introduction to Computing, 3rd ed. 34 Input Expressions Form input_stream >> variable; May be chained together cin >> x >> y; Adapts to whatever type variable is User must enter correct type Best to prompt user for input expected cout << "Enter choice (1 – 10) : "

C++ An Introduction to Computing, 3rd ed. 35 Output Expressions Form output_stream << expression; May be chained cout << "The sum = " << sum; The expression can be a variable, a constant or a combination using operators cout << "Sum = " << v1 + v2 + v3; The expression adapts to whatever types are used

C++ An Introduction to Computing, 3rd ed. 36 Output Formatting Possible to specify appearance of output From iostream:(for your reference) showpoint Display decimal point and trailing zeros for all real numbers. noshowpoint Hide decimal point and trailing zeros for whole real numbers (default). fixed Use fixed-point notation for real values. scientific Use scientific notation for real values. boolalpha Display boolean values as strings “true” and “false”. left Display values left justified within a field. right Display values right justified within a field (default). From iomanip:(will be used in this semester) setw(w) Display the next value in a field of size w (default 1). setprecision(p) Display p fractional digits for all subsequent output of real values (common default is 6). Must specify the proper include files to use these. #include #include using namespace std;

C++ An Introduction to Computing, 3rd ed. 37 Objected-Centered Design Problem: A manufacturing company uses trucks for delivery. For each trip, the driver records mileage, gallons of fuel, cost of fuel, etc. The accountants want a report for miles per gallon, total trip cost, cost per mile. The controller wants a program to assist in recording and calculating these statistics

C++ An Introduction to Computing, 3rd ed. 38 Behavior For trip statistics: Enter miles traveled: 99 Enter gallons fuel: Enter cost per gallon : Enter per mile cost for this truck: 9.99 Mileage for this trip : Total trip cost : Trip cost per mile: 99.99

C++ An Introduction to Computing, 3rd ed. 39 Objects Description Software Objects TypeKindName screen ostream variable cout total miles traveled double variable miles total gallons used double variable gallonsOfFuel fuel cost per gallon double variable unitFuelCost operating cost/mi double variable unitOperatingCost keyboard istream variable cin miles per gallon double variable milesPerGallon total cost of trip double variable totalTripCost cost per mile double variable costPerMile

C++ An Introduction to Computing, 3rd ed. 40 Operations i. Display prompt on screen for input ii. Read sequence of four reals from keyboard iii. Compute mpg divide miles by number of gallons iv. Compute total cost of trip: add.. cost of fuel = gallons * price / gallon operating costs = miles * cost / mile v. Compute cost of trip per mile Divide total cost by number of miles traveled vi. Output real values

C++ An Introduction to Computing, 3rd ed. 41 Algorithm 1. Display a prompt via cout for miles, gallonsOfFuel, unitFuelCost, and unitOperatingCost. 2. Read values from cin into miles, gallonsOfFuel, unitFuelCost, and unitOperatingCost. 3. Check that each of these values is positive. 4. Compute milesPerGallon = miles / gallonsOfFuel. 5. Compute fuelCost = gallonsOfFuel * unitFuelCost. 6. Compute operatingCost = unitOperatingCost * miles. 7. Compute totalTripCost = fuelCost + operatingCost. 8. Compute costPerMile = totalTripCost / miles. 9. Via cout, display milesPerGallon, totalTripCost and costPerMile, with descriptive labels.

C++ An Introduction to Computing, 3rd ed. 42 Coding, Execution, Testing View source code Figure 3.2Figure 3.2 Note use of prompting input expressions formatting of output View sample runssample runs