Expressions Version 1.0 1. Topics Arithmetic expressions Conversions Operator precedence String class 2.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
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.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
CS 106 Introduction to Computer Science I 01 / 30 / 2008 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Basic Elements of C++ Chapter 2.
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
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
LESSON 6 – Arithmetic Operators
Chapter 2: Using Data.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Mathematical Calculations in Java Mrs. C. Furman.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Two: Fundamental Data Types Slides by Evan Gallagher.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Recap……Last Time [Variables, Data Types and Constants]
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
What are Operators? Some useful operators to get you started.
Programming Fundamentals. Summary of Previous Lectures Phases of C++ Environment Data Types cin and cout.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Dr. Sajib Datta Jan 21,  Declare a variable ◦ int height; [note that no value is still assigned]  Assign a variable a value ◦ height =
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
1 09/10/04CS150 Introduction to Computer Science 1 What Actions Do We Have Part 2.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter Topics The Basics of a C++ Program Data Types
Expressions.
Chapter 7: Expressions and Assignment Statements
Expressions.
Lecture 3: Operators, Expressions and Type Conversion
Programming Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Chapter 7: Expressions and Assignment Statements
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Basic Elements of C++ Chapter 2.
Operators and Expressions
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Introduction to C++ Programming
Arithmetic Expressions & Data Conversions
Expressions and Assignment
elementary programming
Data Types and Expressions
Engineering Problem Solving with C++ An Object Based Approach
Primitive Types and Expressions
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

Expressions Version 1.0 1

Topics Arithmetic expressions Conversions Operator precedence String class 2

Objectives At the completion of this topic, students should be able to: Correctly use all arithmetic operators in a C++ program Correctly write arithmetic expressions in a C++ program and be able to explain how expressions are evaluated Explain how and when data type conversions are done in C++ Correctly use type casting in a C++ program Understand how operator precedence affects the evaluation of an expression in a C++ program, and know the precedence of arithmetic operators in C++ Correctly use objects of the string class in a program 3

Arithmetic Expressions Expressions are combinations of operators and operands that define some operation to be performed by the computer. sum = numOne + numTwo; area = PI * radius * radius; we usually put a space on either side of the operator to make the expression more readable. 4

Arithmetic Operators +plusc = a + b; -minusc = a – b; *timesc = a * b; /divide byc = a / b; //integer or real division %modulusc = a % b; //integers only operator meaning example 5

Remainder Operator The remainder operator is the % symbol It only works with integers Sometimes called the modulus operator int a = 5; int b = 3; int c = a % b; the result is 2 … divide 5 by 3, the remainder is 2. The sign of the result is the same as the sign of the numerator, 6

Arithmetic Assignment Instead of writing total = total + 3; we can use the shorthand arithmetic assignment operator total += 3; total -= 3;total = total -3; total *= 3;total = total * 3; total /= 3;total = total / 3; total %= 3;total = total % 3; expression roperand = loperand is the same as 7

Increment Operator Adding one to a variable is done so often in programs that a shortcut method has been provided in C++ to write it. Instead of writing total = total + 1; we can write total++; 8

pre- and post-increment Using the increment operator is complicated by the fact that you can do a pre-increment or a post-increment. total++post-increment ++totalpre-increment What’s the difference? This is best illustrated by example. 9

Consider the following statements: int height = 5; int length = 4; int total = height * length++; totalheightlength The increment is done after the multiplication. 10

Consider the following statements: int height = 5; int length = 4; int total = height * ++length; totalheightlength The increment is done before the multiplication. 11

Decrement Operator Instead of writing total = total – 1; we can write total--; There is a pre and a post-decrement. 12

Mixed Data Types area = width * height; an operator, like * has two operands. It is called a binary operator. the operands may not be of the same type. If they are not, C++ tries to make sense of the operation by converting one operand so that it matches the other. It will always convert to a ‘higher’ data type if required. long double double float long int short char 13

Example int count = 7; float avgWeight = 155.5F; double totalWeight = count * avgWeight; totalWeightavgWeightcount = * temporary float variable 7.0 temporary float variable avgWeight *

Data Conversion Remember that all data in C++ is typed Sometimes it is necessary to change data from one data type to another. There are two types of conversions: Widening Conversions the new type uses an equal or greater amount of storage for example, converting a byte to an int. Narrowing Conversions the new type uses less storage 15

Widening Conversions FromTo charshort, int, long, float, double shortint, long, float, double intlong, float, double longfloat, double floatdouble doublelong double (later) note: converting an int to a float or a long to a double may result in a loss of precision. 16

Narrowing Conversions FromTo shortchar intshort, char longshort, char, int floatshort, char, int, long doubleshort, char, int, long, float 17

Conversions Occur When: A value of one type is assigned to a variable of a different type. A value must be promoted to a different type in order for an operation to work correctly. The programmer explicitly casts a value to a different type. 18

Assignment Conversion Assignment conversions only work if the conversion is a widening conversion! int dollars = 42; double money; money = dollars; double money = 42.50; int dollars; dollars = money; compiler warning! implicit (compiler)explicit (cast) 19

Arithmetic Promotion double sum = 25.50; int count = 5; result = sum / count; In order for the computer to do this division, both numerator and denominator must be real numbers. So, count is first promoted to a double, then the division is performed. 20

Type Casting Casting is used to explicitly convert from one data type to another. Casts can do both widening and narrowing conversions. int dollars; double money = 35.50; dollars = (int) money; the data type in parentheses tells the computer what data type money is to be converted to. In this case, the value of will be converted to an integer. This results in the.50 being truncated. The resulting integer is then assigned to dollars. 21

C++ Casts In C++ we usually use the more modern type casts. int dollars; float money = 35.50; dollars = static_cast (money); or dollars = (int)money; new C++ casting (doubtful use?) a static_cast is checked at compile time 22

Other Type Casts For now, the static_cast will do everything that we need. However, in the future we will run across other type casts which we will only mention here. Just use (cast)! const_cast dynamic_cast reinterpret_cast 23

Operator Precedence What is the result of the expression x = / 2; It depends upon whether we do the addition first or the division first! 14 + ( 8 / 2 ) = = 18 ( ) / 2 = 22 / 2 = 11 24

In C++, multiplication, division, and the remainder operator have the same precedence. Addition and subtraction have the same precedence. Multiplication, division and remainder are always done before addition and subtraction. If two operators have the same precedence they are evaluated left to right. You can change the order of evaluation by using parentheses. When in doubt use (‘s. 25

int varOne = 5; int varTwo = 7; double result = varTwo / varOne; the answer is 1.0. Why? When doing integer division, the result will always be an integer. Any fractional part is truncated, even when it is stored in a real variable. Integer Division 26

The String Class In C++, we represent strings of text data using objects of the string class. You may also see programs where strings of text data are represented as arrays of characters. This is an earlier style of coding that comes from the C language called c- strings. Because you will see programs that store text data in character arrays, we will discuss this in a later section. 27

Because String objects are used so frequently C++ provides a shorthand notation for creating and initializing a string object string course = “CS 1400”; #include using namespace std; we could also write string course (“CS 1400”); 28

String Functions Two strings can be concatenated using the + operator string s1 = “hello”; string s2 = “ world”; string s3 = s1 + s2; We will look at other string functions later. 29

Inputting Strings The >> operator is overloaded to work with string objects. However, we must be careful. Consider the following: string str1; cin >> str1; getline(cin,str1); What happens when the user types “cat” and hits the enter key? 30

keyboard buffer cin string str1; cin >> str1; str1 cat\n reading stops when white space is encountered keyboard buffer c a t note that the buffer pointer is now pointing at the new line character. It remains in the buffer. 31

keyboard buffer cin string str1; cin >> str1; str1 The yellow cat\n reading stops when white space is encountered keyboard buffer The note that the buffer pointer is now pointing at the space character. The rest of the string stays in the buffer. What happens when the user types “The yellow cat”? 32

In order to read the entire string from the keyboard buffer, we must use the getline function that works with the string class. It looks like this: string response; getline (cin, response); 33

String Functions Constructors string str; default constructor, creates an empty string string str (“hello”); creates a string object with the data “hello” string str (astring); creates a string object with the data that is a copy of the data in the string object astring. 34

String Functions Element Access str[ i ] returns the character at position i in the string str. str.at(i) returns the character at position i in the string str. str.substr(pos, len) returns the substring from str that begins with pos and having len characters. str.length( ) returns the length of the string. 35

String Functions Assignment/Modifiers str1 = str2; copies the data from str2 into str1. The length of str1 is set to that of str2. str1 += str2; the data from str2 is concatenated to str1 and str1’s length adjusted accordingly. str.empty( ); returns true if str is an empty string. str.find (str1); returns the index of the first occurrence of str1 in the string str. 36

Practice Given: int a = 12; int b = 5; What is int c = a % b; 37

Practice Given: double a = 6.5; double b = 5.0; What is int c = a % b; 38

Practice Given: int a = 10; int b = 2; After int c = a++ * b; int d = ++a * b++; What are the values of a, b, and c? 39

Practice Given: double a = 6.5; int b = 5; What is int c = a * b; 40

Practice Given: double a = 6.5; int b = 5; What is double c = a * b; 41

Practice Given: int a = 14; int b = 5; What is double c = a / b; 42

double w = 12.0; double y = 3.0; double z = 5.0 a = w / z; b = w – z / y; c = (w – z) / y; d = w – ( z * y ); e = w – z * y; f = (w – z) * y; assume that these are all declared as doubles. Practice 43

Practice Given: int a; When executing the statement cin >> a; what stops the read operation? 44

Joe Clockwatcher 45