Download presentation
Presentation is loading. Please wait.
1
Lecture 2B Expressions Richard Gesick
Figures from Lewis, “C# Software Solutions”, Addison Wesley
2
Topics Expressions Data Conversion Standard IO Basic Libraries
3
Expression Combination of one or more operators and operands
Has both data type & value Operands may be literals constants variables
4
Arithmetic Operators Operator Operation + addition - subtraction *
multiplication / division % modulus (remainder after division between 2 integers)
5
Integer Division & Modulus
When dividing two integers: the quotient is an integer the remainder is truncated (discarded) To get the remainder, use the modulus operator with the same operands
6
Examples 8 25 / 3 25 % 3 3 / 25 3 % 25 25.0 / 5 10 / 3.0 1 3 5.0
7
Operator Precedence Precedence Operator Associativity 1
Parenthesis: () Innermost First 2 Unary operators: (type) Right to left 3 Binary operators: * / % Left to right 4 + - 5 Assignment Operators = += -= *= /= %= Copyright © 2012 Pearson Education, Inc.
8
Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
9
Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side
10
Assignment Revisited First the expression on the right hand
side of the = operator is evaluated Expression has data type and value variable = expression; Then the result is stored in the variable on the left hand side (has data type), if types are compatible
11
Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)
12
Shortcut Operators ++ increment by 1 -- decrement by 1 Example:
count++; // count = count + 1; count--; // count = count - 1;
13
Increment and Decrement
The increment and decrement operators can be applied in postfix form: count++ or prefix form: ++count When used as part of a larger expression, the two forms can have different effects Because of their subtleties, the increment and decrement operators should be used with care
14
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 USE EITHER dogs-- ; dogs;
15
BUT... when the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results LET’S SEE HOW. . .
16
PREFIX FORM “First increment, then use ”
int alpha ; int num ; num = 13; alpha = ++num * 3; 13 num 14 alpha 42
17
POSTFIX FORM “Use, then increment ”
int alpha ; int num ; num = 13; alpha = num++ * 3; 13 num alpha 13 39 num alpha 14 num
18
More Shortcut Operators
Example Equivalent += a += 3; a = a + 3; -= a -= 10; a = a - 10; *= a *= 4; a = a * 4; /= a /= 7; a = a / 7; %= a %= 10; a = a % 10;
19
Assignment Operators is equivalent to
The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);
20
Common Error Trap No spaces are allowed between the arithmetic operator and the equals sign Note that the correct sequence is +=, not =+ Example: add 2 to a // incorrect a =+ 2; // a = +2; assigns 2 to 2 // correct a += 2; // a = a + 2;
21
Topics Expressions Data Conversion
22
Assigning the Values of Other Variables
Syntax: dataType variable2 = variable1; Rules: 1. variable1 needs to be defined before this statement appears in the source code 2. variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2.
23
Mixed-Type Arithmetic
When performing calculations with operands of different data types: Lower-precision operands are promoted to higher-precision data types, then the operation is performed Promotion is effective only for expression evaluation; not a permanent change Called "implicit type casting" Bottom line: any expression involving a floating-point operand will have a floating-point result.
24
Two types of data conversion
Widening conversion (promotion) safe, do not lose data goes to a “wider” (more bits) data type may lose precision (long to float) Narrowing conversion (demotion) may lose data may lose precision should be avoided compiler error unless specific cast done
25
Copyright © 2012 Pearson Education, Inc.
Order of Types Because different types are different representations, frequently we need to convert between types. Sometimes these conversions may lose information. Conversion from lower types to higher types results in no loss of information. Conversion from higher types to lower types may loose information. High: Low: long double double float long integer integer short integer Copyright © 2012 Pearson Education, Inc.
26
Conversion Techniques
assignment conversion assign an int to a long promotion divide an int by a double casting
27
Explicit Type Casting Syntax: (dataType)( expression )
Note: parentheses around expression are optional if expression consists of 1 variable Useful for calculating averages double result = (double) 25 / 3; double result = (double) total / count;
28
Overflow and Underflow
answer too large to store Example: using 16 bits for integers result = ; Exponent overflow answer’s exponent is too large Example: using float, with exponent range –38 to 38 result = 3.25e28 * 1.0e15; Exponent underflow answer’s exponent too small result = 3.25e-28 *1.0e-15; Copyright © 2012 Pearson Education, Inc.
29
Standard Input / Output
Copyright © 2012 Pearson Education, Inc.
30
C++ Input/Output No built-in I/O in C++
A library provides input stream and output stream Keyboard Screen executing program istream ostream 30
31
<iostream> Header File
Access to a library that defines 3 objects An istream object named cin (keyboard) An ostream object named cout (screen) An ostream object named cerr (screen) 31
32
Giving a Value to a Variable
In your program you can assign (give) a value to the variable by using the assignment operator = ageOfDog = 12; or by another method, such as cout << “How old is your dog?”; cin >> ageOfDog;
33
>> Operator >> is called the input or extraction operator
>> is a binary operator >> is left associative Expression Has value cin >> age cin Statement cin >> age >> weight;
34
Extraction Operator (>>)
Variable cin is predefined to denote an input stream from the standard input device((the keyboard) The extraction operator >> called “get from” takes 2 operands; the left operand is a stream expression, such as cin--the right operand is a variable of simple type
35
Extraction Operator (>>)
Operator >> attempts to extract (inputs) the next item from the input stream and to store its value in the right operand variable >> “skips over” (actually reads but does not store anywhere) leading white space characters as it reads your data from the input stream(either keyboard or disk file)
36
Input Statements SYNTAX These examples yield the same result.
cin >> length; cin >> width; cin >> length >> width; cin >> Variable >> Variable . . .;
37
Whitespace Characters Include . . .
blanks tabs end-of-line (newline) characters newline character created by: hitting Enter or Return at the keyboard or by using the manipulator endl or by using the symbols "\n" in the program
38
At keyboard you type: A[space]B[space]C[Enter]
char first; char middle; char last; cin >> first ; cin >> middle ; cin >> last ; NOTE: A file reading marker is left pointing to the newline character after the ‘C’ in the input stream first middle last ‘A’ ‘B’ ‘C’ first middle last
39
At keyboard you type: [space]25[space]J[space]2[Enter]
int age; char initial; float bill; cin >> age; cin >> initial; cin >> bill; NOTE: A file reading marker is left pointing to the newline character after the 2 in the input stream age initial bill 25 ‘J’ 2.0
40
Keyboard and Screen I/O
#include <iostream> Keyboard Screen executing program input data output data cin (of type istream) cout (of type ostream)
41
NOTE: shows the location of the file reading marker
STATEMENTS CONTENTS MARKER POSITION int i; A\n char ch; \n float x; cin >> i; A\n 16.9\n cin >> ch; A\n cin >> x; A\n i ch x 25 i ch x 25 ‘A’ i ch x 25 ‘A’ 16.9 i ch x
42
Another Way to Read char Data
The get() function can be used to read a single character. get() obtains the very next character from the input stream without skipping any leading whitespace characters
43
At keyboard you type: A[space]B[space]C[Enter]
char first; char middle; char last; cin.get(first); cin.get(middle); cin.get(last); NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream first middle last ‘A’ ‘ ’ ‘B’ first middle last 43
44
Use function ignore() to skip characters
The ignore() function is used to skip (read and discard) characters in the input stream The call: cin.ignore(howMany, whatChar); will skip over up to howMany characters or until whatChar has been read, whichever comes first
45
NOTE: shows the location of the file reading marker
STATEMENTS CONTENTS MARKER POSITION int a; \n int b; \n int c; cin >> a >> b; \n \n cin.ignore(100, ‘\n’); \n cin >> c; \n a b c 957 34 a b c 957 34 a b c 957 34 128 a b c
46
Another Example Using cin.ignore()
NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int i; A 22 B 16 C 19\n char ch; cin >> ch; A 22 B 16 C 19\n cin.ignore(100, ‘B’); A 22 B 16 C 19\n cin >> i; A 22 B 16 C 19\n i ch ‘A’ 957 34 i ch ‘A’ 957 34 i ch 16 ‘A’ 957 34 i ch
47
String Input in C++ Input of a string is possible using the extraction operator >> Example string message; cin >> message; cout << message; However . . .
48
>> Operator with Strings
Using the extraction operator(>>) to read input characters into a string variable The >> operator skips any leading whitespace characters such as blanks and newlines It then reads successive characters into the string >> operator then stops at the first trailing whitespace character (which is not consumed, but remains waiting in the input stream)
49
String Input Using >>
string firstName; string lastName; cin >> firstName >> lastName; Suppose input stream looks like this: Joe Hernandez 23 What are the string values?
50
Results Using >>
string firstName; string lastName; cin >> firstName >> lastName; Result “Joe” “Hernandez” firstName lastName
51
getline() Function Because the extraction operator stops reading at the first trailing whitespace, >> cannot be used to input a string with blanks in it Use the getline function with 2 arguments to overcome this obstacle First argument is an input stream variable, and second argument is a string variable Example string message; getline(cin, message);
52
getline(inFileStream, str)
getline does not skip leading whitespace characters such as blanks and newlines getline reads successive characters(including blanks) into the string, and stops when it reaches the newline character ‘\n’ The newline is consumed by getline, but is not stored into the string variable
53
String Input Using getline
string firstName; string lastName; getline(cin, firstName); getline(cin, lastName); Suppose input stream looks like this: Joe Hernandez 23 What are the string values?
54
Results Using getline string firstName; string lastName;
getline(cin, firstName); getline(cin, lastName); “ Joe Hernandez 23” ? firstName lastName
55
Interactive I/O In an interactive program the user enters information while the program is executing Before the user enters data, a prompt should be provided to explain what type of information should be entered The amount of information needed in the prompt depends on the complexity of the data being entered, and the sophistication of the person entering the data
56
Prompting for Interactive I/O
// Pattern: cout(prompt) cin(read value) cout << “Enter part number : “ << endl; cin >> partNumber; cout << “Enter quantity ordered : “ << endl; cin >> quantity; cout << “Enter unit price : “ << endl; cin >> unitPrice; // Calculate and print results
57
Prompting for Interactive I/O, cont...
totalPrice = quantity * unitPrice; cout << “Part # “ << partNumber << endl; cout << “Quantity: “ << quantity << endl; cout << “Unit Cost: $ “ << setprecision(2) << unitPrice << endl; cout << “Total Cost: $ “ << totalPrice
58
Manipulators and Methods
endl – places a newline character in the output buffer and flushes the buffer. setf() and unsetf() Flag Meaning ios::showpoint display the decimal point ios::fixed fixed decimal notation ios::scientific scientific notation Ios::setprecision(n) set the number of significant digits to be printed to the integer value n Ios::setw(n) set the minimum number of columns for printing the next value to the integer value n ios::right right justification ios::left left justification Copyright © 2012 Pearson Education, Inc.
59
Building C++ Solutions with IDEs
Copyright © 2012 Pearson Education, Inc.
60
Integrated Development Environments (IDEs)
IDEs are software packages designed to facility the development of software solutions. IDEs include: Code editors Compiler Debugger Testing tools Many additional helpful tools…
61
Basic Functions in C++ Standard Library
62
Basic C++ Math Functions
fabs(x) computes absolute value of x sqrt(x) computes square root of x, where x >=0 pow(x,y) computes xy ceil(x) nearest integer larger than x floor(x) nearest integer smaller than x exp(x) computes ex log(x) computes ln x, where x >0 log10(x) computes log10x, where x>0
63
Trigonometric Functions
sin(x) sine of x, where x is in radians cos(x) cosine of x, where x is in radians tan(x) tangent of x, where x is in radians asin(x) This function computes the arcsine, or inverse sine, of x, where x must be in the range [−1, 1]. The function returns an angle in radians in the range [−π/2, π/2]. acos(x) This function computes the arccosine, or inverse cosine, of x, where x must be in the range [−1, 1]. The function returns an angle in radians in the range [0, π]. atan(x) This function computes the arctangent, or inverse tangent, of x. atan2(y,x) This function computes the arctangent or inverse tangent of the value y/x. The function returns an angle in radians in the range [−π, π].
64
Common Functions Defined in <cctype>
isalpha(ch) Returns true if ch is an upper or lower case letter. isdigit(ch) Returns true if ch is a decimal digit isspace(ch) Returns true if ch is a whitespace character. islower(ch) Returns true if ch is an lower case letter. isupper(ch) Returns true if ch is an upper case letter. tolower(ch) Returns the lowercase version of ch if ch is an uppercase character, returns ch otherwise. toupper(ch) Returns the uppercase version of ch if ch is a lowercase character, returns ch otherwise.
65
Copyright © 2012 Pearson Education, Inc.
System Limitations C++ standards do not specify limitations of data types – they are compiler-specific. C++ does provide standard methods of accessing the limits of the compiler: <climits> defines ranges of integer types. <cfloat> defines ranges of floating-point types. the sizeof(type) function returns the memory size of the type, in bytes. Copyright © 2012 Pearson Education, Inc.
66
Summary What did you learn?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.