Arithmetic Expressions
- how to write arithmetic expressions on double and int data types
- arithmetic operators: +, -, *, /, % (remainder)
o division with 0 is undefined (causing run-time error)
o m = (m/n)*n + m%n
- data type of an expression
o x+y is int if both x and y are int
o x+y is double is either x or y are double (this includes mixed type expressions)
- how assignment works
o assign statement is executed according to the mixed-type rules
o the result is stored in the variable on the left
e.g. y = m/n; if y is int type, only integral part of division m/n is saved
- Type casts
o if m and n are int type (e.g. m = 5, n = 2), the value of y after the statement y = m/n is 2, even if y is of double type!
o To prevent such behavior, type casts are used:
y = (double) m / (double) n; or,
y
= (double) m / n;
- + and - can be unary or binary operators
o x = -y; /*
unary */
o z = y - x; /*
binary */
- Rules for evaluating expressions:
o Parenthesis rule (executed from the inside out)
o Operator precedence:
§ unary +, -
§ *, /, %
§ binary +, -
o Associativity: evaluate operators of the same precedence from left to right
§
x * y *
z + a / b – c * d = (x*y*z) + (a/b) – (c*d)
o look at examples from Table 2.10 in the textbook
Formatting Numbers in Program Output
- read section 2.6 from the textbook
- pay attention to Tables 2.11, 2.12, 2.13
Interactive Mode
- Two modes of computer operation:
o interactive: interacts with user (like in Lab 1 assignment)
o batch: scans data from a file
- Input redirection:
o “conversion <mydata” uses data from file “mydata”as input
o note: in this case, there is no need for printf prompt to user to enter data
- Output redirection
o “conversion <mydata >myoutput” also outputs the results to file “myoutput”
Common Programing Errors
- Syntax errors – compiler cannot translate it. Typical errors:
o missing semicolomn
o undeclared variable
o comment not closed
- Run-time errors – program directs computer to perform illegal operation. Example:
o dididing by zero
- Undetected errors – program gives incorrect result
- Logic errors – caused by faulty algorithms. Example:
o kms = 1.235*miles;