Lecture 2B Expressions Richard Gesick

Slides:



Advertisements
Similar presentations
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.
Advertisements

CS1 Lesson 3 Expressions and Interactivity CS1 -- John Cole1.
1 9/13/06CS150 Introduction to Computer Science 1 Type Casting.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
1 Engineering Problem Solving with C++ An Object Based Approach Chapter 2 Simple C++ Programs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
Expressions, Data Conversion, and Input
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
Copyright © 2012 Pearson Education, Inc. Chapter 2 Simple C++ Programs.
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
1 Chapter 4 Program Input and the Software Design Process.
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.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems.
Simple C++ Programs Program Structure Constants and Variables
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Expressions and Interactivity. 3.1 The cin Object.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Chapter 4 Program Input and the Software Design Process.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
2/4/2016Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs.
1 Chapter 4 Program Input and the Software Design Process.
Math Operators and Output Formatting. Incrementing and Decrementing StatementEquivalent Counter++;Counter = Counter + 1; ++Counter;Counter = Counter +
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
CS221 C++ Basics. C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 4 Program Input and the Software Design Process
Variables, Operators, and Expressions
Simple C Programs.
Operations Making Things Happen.
Lecture 3 Expressions, Type Conversion, Math and String
Today Variable declaration Mathematical Operators Input and Output Lab
Chapter 2 Introduction to C++ Programming
Chapter 3 Assignment and Interactive Input.
BIL 104E Introduction to Scientific and Engineering Computing
Chapter 2 Assignment and Interactive Input
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Copyright © 2012 Pearson Education, Inc.
Expressions and Interactivity
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Introduction to C++ Programming
A First Book of ANSI C Fourth Edition
Chapter 3: Input/Output
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Chapter 4 Program Input and the Software Design Process
CS150 Introduction to Computer Science 1
Data Types and Expressions
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Dale/Weems/Headington Program Input and the Software Design Process
C++ for Engineers and Scientists Second Edition
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Lecture 2B Expressions Richard Gesick Figures from Lewis, “C# Software Solutions”, Addison Wesley

Topics Expressions Data Conversion Standard IO Basic Libraries

Expression Combination of one or more operators and operands Has both data type & value Operands may be literals constants variables

Arithmetic Operators Operator Operation + addition - subtraction * multiplication / division % modulus (remainder after division between 2 integers)

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

Examples 8 25 / 3 25 % 3 3 / 25 3 % 25 25.0 / 5 10 / 3.0 1 3 5.0 3.33333

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.

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

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

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

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)

Shortcut Operators ++ increment by 1 -- decrement by 1 Example: count++; // count = count + 1; count--; // count = count - 1;

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

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;

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. . .

PREFIX FORM “First increment, then use ” int alpha ; int num ; num = 13; alpha = ++num * 3; 13 num 14 alpha 42

POSTFIX FORM “Use, then increment ” int alpha ; int num ; num = 13; alpha = num++ * 3; 13 num alpha 13 39 num alpha 14 num

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;

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);

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;

Topics Expressions Data Conversion

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.

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.

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

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.

Conversion Techniques assignment conversion assign an int to a long promotion divide an int by a double casting

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;

Overflow and Underflow answer too large to store Example: using 16 bits for integers result = 32000 +532; 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.

Standard Input / Output Copyright © 2012 Pearson Education, Inc.

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

<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

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;

>> 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;

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

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)

Input Statements SYNTAX These examples yield the same result. cin >> length; cin >> width; cin >> length >> width; cin >> Variable >> Variable . . .;

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

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

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

Keyboard and Screen I/O #include <iostream> Keyboard Screen executing program input data output data cin (of type istream) cout (of type ostream)

NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int i; 25 A\n char ch; 16.9\n float x; cin >> i; 25 A\n 16.9\n cin >> ch; 25 A\n cin >> x; 25 A\n i ch x 25 i ch x 25 ‘A’ i ch x 25 ‘A’ 16.9 i ch x

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

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

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

NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int a; 957 34 1235\n int b; 128 96\n int c; cin >> a >> b; 957 34 1235\n 128 96\n cin.ignore(100, ‘\n’); 957 34 1235\n cin >> c; 957 34 1235\n a b c 957 34 a b c 957 34 a b c 957 34 128 a b c

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

String Input in C++ Input of a string is possible using the extraction operator >> Example string message; cin >> message; cout << message; However . . .

>> 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)

String Input Using >> string firstName; string lastName; cin >> firstName >> lastName; Suppose input stream looks like this: Joe Hernandez 23 What are the string values?

Results Using >> string firstName; string lastName; cin >> firstName >> lastName; Result “Joe” “Hernandez” firstName lastName

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);

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

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?

Results Using getline string firstName; string lastName; getline(cin, firstName); getline(cin, lastName); “ Joe Hernandez 23” ? firstName lastName

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

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

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

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.

Building C++ Solutions with IDEs Copyright © 2012 Pearson Education, Inc.

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…

Basic Functions in C++ Standard Library

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

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 [−π, π].

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.

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.

Summary What did you learn?