In the previous lesson you learnt about casting.
Arithmetic operations on primitives
Enter your text here ...
The arithmetic operators are:
- + for addition: e.g., a + b
- - for subtraction: e.g., a - b
- * for multiplication: e.g., a * b
- / for division: e.g., a / b
- % for modulus (i.e., the remainder after division) : e.g., a % b
- ++ for increment by 1: e.g., a++ or ++a
- -- for decrement by 1: e.g., a-- or --a
Take careful note of how the following calculations are performed:
// Division
double d = 3.0 / 4.0; // d becomes 0.75
int i = 3 / 4; // i becomes 0 (int has no decimals)
int j = 15 / 2; // j becomes 7
// if either value is floating point, the result will be as well
double e = 15 / 2.0; // e becomes 7.5
// here both operands are int so that is computed first
double f = 15 / 2; // f becomes 7.0
// modulus (remainder after division)
int k = 34 % 5; // k becomes 4
double g = 3.5 % 2.1; // f becomes 1.4
// negation
int a = 2;
int b = -a; // b becomes -2 (- is prefix op rather than
subtraction here)
// precedence rules – use brackets to avoid ambiguity
int p = 3 + (4 * 5); // p becomes 23
int q = (3 + 4) * 5; // q becomes 35
// increment & decrement (++, --)
int r = 10;
int s = r++; // r becomes 11, but s becomes 10...!!!
r = 10;
s = ++r; // now both r and s will be 11
In the next section of lessons you will learn about arrays, loops, and sorts.
Comments