COP 3275: Chapter 04. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Similar documents
Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen. Introduction

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Operators & Expressions

Lecture 3. More About C

Introducing C. Origins of C. Chapter 1. Standardization of C. Origins of C

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Unit 3. Operators. School of Science and Technology INTRODUCTION

Operators and Expressions:

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

PART II. Computation

Operators in C. Staff Incharge: S.Sasirekha

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Programming in C++ 5. Integral data types

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Programming for Engineers Iteration

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Chapter 3 Structure of a C Program

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

COP 3275: Chapter 09. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Operators And Expressions

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Information Science 1

Basic Assignment and Arithmetic Operators

Chapter 4: Basic C Operators

Programming for Electrical and Computer Engineers. Loops

Expression and Operator

C Programming

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Goals of this Lecture

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

(2-1) Numeric Expressions in C H&K Chapter 2. Instructor - Andrew S. O Fallon CptS 121 (August 27, 2018) Washington State University

Chapter 2, Part III Arithmetic Operators and Decision Making

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Computer Programming CS F111

Structured programming. Exercises 3

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Chapter 3: Operators, Expressions and Type Conversion

Data Types and Variables in C language

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

LECTURE 3 C++ Basics Part 2

Introduction to C Programming (Part A) Copyright 2008 W. W. Norton & Company. All rights Reserved

Arithmetic Operators. Portability: Printing Numbers

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Ch. 12: Operator Overloading

Lecture 4 CSE July 1992

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

JAVA OPERATORS GENERAL

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

1.3b Type Conversion

Add Subtract Multiply Divide

Programming for Engineers Introduction to C

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Formatted Input/Output

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Part I Part 1 Expressions

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Programming for Electrical and Computer Engineers. Pointers and Arrays

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

ECE 122 Engineering Problem Solving with Java

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

C/C++ Programming for Engineers: Working with Integer Variables

Chapter 7. Basic Types

CS102: Variables and Expressions

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Basics of Programming

Operator precedence and associativity

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Chapter 12 Variables and Operators

Fundamentals of Programming Session 7

Lecture 3 Tao Wang 1

CIS133J. Working with Numbers in Java

Fundamentals of Programming Session 20

COP 3275: Chapter 07. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Section we will not cover section 2.11 feel free to read it on your own

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Fundamental of Programming (C)

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

More Programming Constructs -- Introduction

Operators. Java operators are classified into three categories:

Full file at C How to Program, 6/e Multiple Choice Test Bank

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

A flow chart is a graphical or symbolic representation of a process.

Expressions and Casting

Department of Computer Science

Information Science 1

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Transcription:

COP 3275: Chapter 04 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Operators C emphasizes expressions rather than statements. Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic operators relational operators logical operators assignment operators increment and decrement operators and many others 2

Arithmetic Operators C provides five binary arithmetic operators: + addition - subtraction * multiplication / division % remainder An operator is binary if it has two operands. There are also two unary arithmetic operators: + unary plus - unary minus 3

Unary Arithmetic Operators The unary operators require one operand: i = +1; j = -i; The unary + operator does nothing. It s used primarily to emphasize that a numeric constant is positive. 4

Binary Arithmetic Operators The value of i % j is the remainder when i is divided by j. 10 % 3 has the value 1, and 12 % 4 has the value 0. Binary arithmetic operators with the exception of % allow either integer or floating-point operands, with mixing allowed. When int and float operands are mixed, the result has type float. 9 + 2.5f has the value 11.5, and 6.7f / 2 has the value 3.35. 5

The / and % Operators The / and % operators require special care: When both operands are integers, / truncates the result. The value of 1 / 2 is 0, not 0.5. The % operator requires integer operands; if either operand is not an integer, the program won t compile. Using zero as the right operand of either / or % causes undefined behavior. The behavior when / and % are used with negative operands is implementation-defined in C89. In C99, the result of a division is always truncated toward zero and the value of i % j has the same sign as i. 6

Implementation-Defined Behavior The C standard deliberately leaves parts of the language unspecified. Leaving parts of the language unspecified reflects C s emphasis on efficiency, which often means matching the way that hardware behaves. It s best to avoid writing programs that depend on implementation-defined behavior. 7

Operator Precedence Does i + j * k mean add i and j, then multiply the result by k or multiply j and k, then add i? One solution to this problem is to add parentheses, writing either (i + j) * k or i + (j * k). If the parentheses are omitted, C uses operator precedence rules to determine the meaning of the expression. 8

Operator Precedence The arithmetic operators have the following relative precedence: Highest:+ - (unary) * / % Lowest: + - (binary) Examples: i + j * k is equivalent to i + (j * k) -i * -j is equivalent to (-i) * (-j) +i + j / k is equivalent to (+i) + (j / k) 9

Operator Associativity Associativity comes into play when an expression contains two or more operators with equal precedence. An operator is said to be left associative if it groups from left to right. The binary arithmetic operators (*, /, %, +, and -) are all left associative, so i - j k is equivalent to (i - j) - k i * j / k is equivalent to (i * j) / k 10

Operator Associativity An operator is right associative if it groups from right to left. The unary arithmetic operators (+ and -) are both right associative, so - + i is equivalent to -(+i) 11

Computing a UPC Check Digit Most goods sold in U.S. and Canadian stores are marked with a Universal Product Code (UPC): First digit: Type of item First group of five digits: Manufacturer Second group of five digits: Product (including package size) Final digit: Check digit, used to help identify an error in the preceding digits 12

How to compute the check digit: Add the first, third, fifth, seventh, ninth, and eleventh digits. Add the second, fourth, sixth, eighth, and tenth digits. Multiply the first sum by 3 and add it to the second sum. Subtract 1 from the total. Compute the remainder when the adjusted total is divided by 10. Subtract the remainder from 9. 13

Program: Computing a UPC Check Digit Example for UPC 0 13800 15173 5: First sum: 0 + 3 + 0 + 1 + 1 + 3 = 8. Second sum: 1 + 8 + 0 + 5 + 7 = 21. Multiplying the first sum by 3 and adding the second yields 45. Subtracting 1 gives 44. Remainder upon dividing by 10 is 4. Remainder is subtracted from 9. Result is 5. 14

Computing a UPC Check Digit The upc.c program asks the user to enter the first 11 digits of a UPC, then displays the corresponding check digit: Enter the first (single) digit: 0 Enter first group of five digits: 13800 Enter second group of five digits: 15173 Check digit: 5 The program reads each digit group as five onedigit numbers. To read single digits, we ll use scanf with the %1d conversion specification. 15

upc.c /* Computes a Universal Product Code check digit */ #include <stdio.h> int main(void) { int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total; printf("enter the first (single) digit: "); scanf("%1d", &d); printf("enter first group of five digits: "); scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5); printf("enter second group of five digits: "); scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5); first_sum = d + i2 + i4 + j1 + j3 + j5; second_sum = i1 + i3 + i5 + j2 + j4; total = 3 * first_sum + second_sum; printf("check digit: %d\n", 9 - ((total - 1) % 10)); } return 0; 16

Assignment Operators Simple assignment: used for storing a value into a variable Compound assignment: used for updating a value already stored in a variable 17

Simple Assignment The effect of the assignment v = e is to evaluate the expression e and copy its value into v. e can be a constant, a variable, or a more complicated expression: i = 5; /* i is now 5 */ j = i; /* j is now 5 */ k = 10 * i + j; /* k is now 55 */ 18

Simple Assignment If v and e don t have the same type, then the value of e is converted to the type of v as the assignment takes place: int i; float f; i = 72.99f; /* i is now 72 */ f = 136; /* f is now 136.0 */ 19

Simple Assignment In many programming languages, assignment is a statement; in C, however, assignment is an operator, just like +. The value of an assignment v = e is the value of v after the assignment. The value of i = 72.99f is 72 (not 72.99). 20

Side Effects An operators that modifies one of its operands is said to have a side effect. The simple assignment operator has a side effect: it modifies its left operand. Evaluating the expression i = 0 produces the result 0 and as a side effect assigns 0 to i. 21

Side Effects Since assignment is an operator, several assignments can be chained together: i = j = k = 0; The = operator is right associative, so this assignment is equivalent to i = (j = (k = 0)); 22

Side Effects Watch out for unexpected results in chained assignments as a result of type conversion: int i; float f; f = i = 33.3f; i is assigned the value 33, then f is assigned 33.0 (not 33.3). 23

Side Effects An assignment of the form v = e is allowed wherever a value of type v would be permitted: i = 1; k = 1 + (j = i); printf("%d %d %d\n", i, j, k); /* prints "1 1 2" */ Embedded assignments can make programs hard to read. They can also be a source of subtle bugs. 24

Lvalues The assignment operator requires an lvalue as its left operand. An lvalue represents an object stored in computer memory, not a constant or the result of a computation. Variables are lvalues; expressions such as 10 or 2 * i are not. 25

Lvalues Since the assignment operator requires an lvalue as its left operand, it s illegal to put any other kind of expression on the left side of an assignment expression: 12 = i; /*** WRONG ***/ i + j = 0; /*** WRONG ***/ -i = j; /*** WRONG ***/ The compiler will produce an error message such as invalid lvalue in assignment. 26

Compound Assignment Assignments that use the old value of a variable to compute its new value are common. Example: i = i + 2; Using the += compound assignment operator, we simply write: i += 2; /* same as i = i + 2; */ 27

Compound Assignment There are nine other compound assignment operators, including the following: -= *= /= %= All compound assignment operators work in much the same way: v += e adds v to e, storing the result in v v -= e subtracts e from v, storing the result in v v *= e multiplies v by e, storing the result in v v /= e divides v by e, storing the result in v v %= e computes the remainder when v is divided by e, storing the result in v 28

Compound Assignment v += e isn t equivalent to v = v + e. One problem is operator precedence: i *= j + k isn t the same as i = i * j + k. There are also rare cases in which v += e differs from v = v + e because v itself has a side effect. Similar remarks apply to the other compound assignment operators. 29

Compound Assignment When using the compound assignment operators, be careful not to switch the two characters that make up the operator. Although i =+ j will compile, it is equivalent to i = (+j), which merely copies the value of j into i. 30

Increment and Decrement Operators Two of the most common operations on a variable are incrementing (adding 1) and decrementing (subtracting 1): i = i + 1; j = j - 1; Incrementing and decrementing can be done using the compound assignment operators: i += 1; j -= 1; 31

Increment and Decrement Operators C provides special ++ (increment) and -- (decrement) operators. The ++ operator adds 1 to its operand. The -- operator subtracts 1. The increment and decrement operators are tricky to use: They can be used as prefix operators (++i and -i) or postfix operators (i++ and i--). They have side effects: they modify the values of their operands. 32

Increment and Decrement Operators Evaluating the expression ++i (a preincrement ) yields i + 1 and as a side effect increments i: i = 1; printf("i is %d\n", ++i); /* prints "i is 2" */ printf("i is %d\n", i); /* prints "i is 2" */ Evaluating the expression i++ (a postincrement ) produces the result i, but causes i to be incremented afterwards: i = 1; printf("i is %d\n", i++); /* prints "i is 1" */ printf("i is %d\n", i); /* prints "i is 2" */ 33

Increment and Decrement Operators ++i means increment i immediately, while i++ means use the old value of i for now, but increment i later. How much later? The C standard doesn t specify a precise time, but it s safe to assume that i will be incremented before the next statement is executed. 34

Increment and Decrement Operators The -- operator has similar properties: i = 1; printf("i is %d\n", --i); /* prints "i is 0" */ printf("i is %d\n", i); /* prints "i is 0" */ i = 1; printf("i is %d\n", i--); /* prints "i is 1" */ printf("i is %d\n", i); /* prints "i is 0" */ 35

Increment and Decrement Operators When ++ or -- is used more than once in the same expression, the result can often be hard to understand. Example: i = 1; j = 2; k = ++i + j++; The last statement is equivalent to i = i + 1; k = i + j; j = j + 1; The final values of i, j, and k are 2, 3, and 4, respectively. 36

Increment and Decrement Operators In contrast, executing the statements i = 1; j = 2; k = i++ + j++; will give i, j, and k the values 2, 3, and 3, respectively. 37

Expression Evaluation Table of operators discussed so far: Precedence NameSymbol(s) Associativity 1 increment (postfix) ++ left decrement (postfix) -- 2 increment (prefix) ++ right decrement (prefix) -- unary plus + unary minus - 3 multiplicative * / % left 4 additive + - left 5 assignment = *= /= %= += -= right 38

Expression Evaluation The table can be used to add parentheses to an expression that lacks them. Starting with the operator with highest precedence, put parentheses around the operator and its operands. Example: a = b += c++ - d + --e / -f Precedence level a = b += (c++) - d + --e / -f 1 a = b += (c++) - d + (--e) / (-f) 2 a = b += (c++) - d + ((--e) / (-f)) 3 a = b += (((c++) - d) + ((--e) / (-f))) 4 (a = (b += (((c++) - d) + ((--e) / (-f))))) 5 39

Order of Subexpression Evaluation The value of an expression may depend on the order in which its subexpressions are evaluated. C doesn t define the order in which subexpressions are evaluated (with the exception of subexpressions involving the logical and, logical or, conditional, and comma operators). In the expression (a + b) * (c - d) we don t know whether (a + b) will be evaluated before (c - d). 40

Order of Subexpression Evaluation Most expressions have the same value regardless of the order in which their subexpressions are evaluated. However, this may not be true when a subexpression modifies one of its operands: a = 5; c = (b = a + 2) - (a = 1); The effect of executing the second statement is undefined. 41

Order of Subexpression Evaluation Avoid writing expressions that access the value of a variable and also modify the variable elsewhere in the expression. Some compilers may produce a warning message such as operation on a may be undefined when they encounter such an expression. 42

Order of Subexpression Evaluation To prevent problems, it s a good idea to avoid using the assignment operators in subexpressions. Instead, use a series of separate assignments: a = 5; b = a + 2; a = 1; c = b - a; The value of c will always be 6. 43

Order of Subexpression Evaluation Besides the assignment operators, the only operators that modify their operands are increment and decrement. When using these operators, be careful that an expression doesn t depend on a particular order of evaluation. 44

Order of Subexpression Evaluation Example: i = 2; j = i * i++; It s natural to assume that j is assigned 4. However, j could just as well be assigned 6 instead: 1. The second operand (the original value of i) is fetched, then i is incremented. 2. The first operand (the new value of i) is fetched. 3. The new and old values of i are multiplied, yielding 6. 45

Undefined Behavior Statements such as c = (b = a + 2) - (a = 1); and j = i * i++; cause undefined behavior. Possible effects of undefined behavior: The program may behave differently when compiled with different compilers. The program may not compile in the first place. If it compiles it may not run. If it does run, the program may crash, behave erratically, or produce meaningless results. Undefined behavior should be avoided. 46

Expression Statements C has the unusual rule that any expression can be used as a statement. Example: ++i; i is first incremented, then the new value of i is fetched but then discarded. 47

Expression Statements Since its value is discarded, there s little point in using an expression as a statement unless the expression has a side effect: i = 1; /* useful */ i--; /* useful */ i * j - 1; /* not useful */ 48

Expression Statements A slip of the finger can easily create a donothing expression statement. For example, instead of entering i = j; we might accidentally type i + j; Some compilers can detect meaningless expression statements; you ll get a warning such as statement with no effect. 49