Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University
Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting programs white spaces comment statements Expressions Arithmetic operators and arithmetic operator precedence Mixed-type arithmetic and type casting Shortcut operators l Quiz 2
Recall Week 08 l Compiler, interpreter l Type, data type, ADT l Declaration l Variable l Constant l Literal l Integer, float, char, boolean l Identifier l Assignment statement 3
Our goals today l To realize the importance of documenting the source code l To understand how to correctly do arithmetic with computers, using high-level programming languages l To understand arithmetic operator precedence 4
White space l To increase readability of your code, surround operators and operands with white space and skip lines between logical sections of program l Space, tab, and new line are white space characters At least one white space character is required between a keyword (reserved word, operator) and identifier Any amount of white space characters are permitted between identifiers, keywords, operators, and literals 5
Comment statements l Comment statements (comments) explain the program to yourself and others There are two types of comments: Block comments Can span several lines Begin with /* and end with */ The compiler ignores everything from /* to */ Line comments Start with // The compiler ignores text from // to the end of line 6
Documenting programs l Always include a block comment at the beginning of each source file (new program) identify the author of the program briefly describe the function of the program l Use line and block comments to explain the logic of the program (for example include pseudocode) always explain constants used (there must be no unexplained magic coefficients ) explain algorithm by default assumptions always explain the program I/O (interface) 7
l Recall assignment statements: <left side> = <right side> Expressions l An expression is a combination of one or more operators and operands that evaluate to a single value, such that: the value is assigned to left side left side is (must be) a single variable or named constant The value must be compatible with (convertible to) the left side s data type 8
Arithmetic expressions l Arithmetic expressions compute numeric results and make use of the arithmetic operators: Operator Operation + addition - subtraction * multiplication / division % modulus (remainder after division) 9
Division and remainder If both operands to the division operator / are integers, the result is an integer (the fractional part is discarded), e.g. 14 / 3 equals to 8 / 12 equals to The remainder modulus operator % (or MOD ) returns the remainder after dividing the first operand by the second, e.g. 14 % 3 equals to 2 8 % 12 equals to 8 Taking modulus is an integer operation both operands must be integers 4 0 10
% usage examples l Remainder operator is very useful in programming. For example: for any even number q, q % 2 is always 0, and for any odd number p, p % 2 is always 1 l Another example: Suppose we know that January 1 is Saturday. We can then easily calculate that the day for February 1 is Tuesday: Saturday is the 6 th day in a week (Sunday is 0 th ) January has 31 days A week has 7 days All this can be written as: (6+31)%7 that gives 2, the second day in a week which is Tuesday 11
Division by zero l Integer division by 0: Example: int x = 4 / 0; l This will result in no compiler error, but at run time, ArithmeticException message (fatal error) will be generated, and the program will stop executing l Floating-point division by 0: If dividend is not 0, the result is Infinity If dividend and divisor are both 0, the result is NaN (not a number) 12
Operator precedence Precedence Operator Order of evaluation Operation 1 ( ) parenthesis for explicit grouping 2 * / % left - right multiplication, division, modulus 3 + - left - right addition, subtraction last = right - left assignment Example: x = a / b * (c + (d - e)) 5 1 4 3 2 13
Expression trees l Sometimes, the evaluation of an expression is convenient to show using an expression tree l The operators lower in the tree have higher precedence for that expression, e.g. a + (b c) / d + a / d b c 14
l In most programming languages, when performing calculations with operands of different data types (on right side): Lower-precision operands are promoted to higher-precision data types, then the calculation is performed Promotion is effective only for expression evaluation and does not cause a permanent change to the data This is called "implicit type casting" l Any expression involving a floating-point operand will have a floating-point result (on right side) 15 Mixed-type arithmetic
16 Rules of promotion Applies the first of these rules that fits: 1. If either operand is a double, the other operand is converted to a double 2. If either operand is a float, the other operand is converted to a float 3. If either operand is a long, the other operand is converted to a long 4. If either operand is an int, the other operand is promoted to an int 5. If neither operand is a double, float, long, or an int, both operands are promoted to int
Examples of promotion int x,y; // integers are 4 bytes using 2's compliment format short z; // shorts are 2 bytes using 2's compliment format float a; // floats are 4 bytes, using floating point format x = 7; z = 3; a = 3.14; y = a * 2 + x/z; Explanation: a = 3.14 (floating point number) '2' is integer but is promoted to '2.0' a floating point number z is a short and will be promoted to an integer x/z involves only integers (7/3) so will give a result of 2 (an integer) then the integer 2 will be promoted to 2.0 (a floating point number) calculation: 3.14 * 2.0 + 2.0 = 8.28 (a floating point number) finally y is assigned an integer 8 since y is an integer data type (the fractional part is removed) 17
18 Explicit type casting l Syntax: (datatype)( expression ) l Examples: float x = 2.5 + (float)5/(float)2; int c = (int)(x 3); l Note that parentheses around an expression with no operators have no effect l Casts are useful for calculating averages (think: why?)
Shortcut operators l ++ is increment by 1, and -- is decrement by 1. Examples: count++; // count = count + 1; count--; // count = count - 1; l Postfix version (var++, var--): use value of var in expression, then increment or decrement l Prefix version (++var, --var): increment or decrement var, then use its value in expression 19
Examples of shortcuts int x,y,z; x = 2; y = 5; z = x++ + y; // first z is 7; then x = 3 x = 2; y = 5; z = ++x + y; // first x = 3; then z is 8 x = 2; y = 5; z = x++ + ++y + y/2; /* is y incremented by ++y before or after y is read for the evaluation of y/2? The result is undefined! */ 20
Note that no spaces are allowed between the arithmetic operator and the equals sign 21 Other shortcut operators Operator 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;
22 Operator precedence Precedence 1 ( ) Operator Order of evaluation Operation parenthesis for grouping ++ -- left - right postincrement, postdecrement 2 ++ -- right - left preincrement, predecrement 3 * / % left - right multiplication, division, modulus 4 + - left - right addition or String concatenation, subtraction 5 = += -= *= /= %= right - left assignment
Real example: C99 operator precedence Precedence Operator Description Associativity 1 ++ -- Suffix/postfix increment and decrement Left-to-right ( ) Function call [ ] Array subscripting. -> Structure and union member access ( type ) { list } Compound literal(c99) 2 ++ -- Prefix increment and decrement Right-to-left + - Unary plus and minus! ~ Logical NOT and bitwise NOT (type) Type cast * Indirection (dereference) & Address-of sizeof Size-of 3 * / % Multiplication, division, and remainder Left-to-right 4 + - Addition and subtraction 5 << >> Bitwise left shift and right shift 6 < <= > >= Relational operators (inequalities) 7 ==!= Relational operators (equalities) 8 & Bitwise AND 9 ^ Bitwise XOR (exclusive or) 10 Bitwise OR (inclusive or) 11 && Logical AND 12 Logical OR 13?: Ternary conditional Right-to-Left 14 = Simple assignment += -= Assignment by sum and difference *= /= %= Assignment by product, quotient, and remainder <<= >>= Assignment by bitwise left shift and right shift &= ^= = Assignment by bitwise AND, XOR, and OR 15, Comma Left-to-right 23
24 Concepts you need to know after this class l White spaces and comment statements: Why we do need to document programs l Arithmetic expressions: Operators and operator precedence (including shortcuts) l Mixed-type arithmetic rules and type casting
25 l Read these slides again l Do the self-preparation assignments l Learn the vocabulary Homework l Consult, whenever necessary, the textbook materials
26 Next class l Boolean expressions Binary logic Relational and logical operators Operator precedence Boolean and algebraic expressions
Quiz 04 27