Programs That Calculate

advertisement
Programs That Calculate
Arithmetic Expressions
+
*
/
addition
subtruction
multiplication
division
 Order of Operations
BEDMAS (brackets, exponentiation, division,
multiplication, addition, subtraction)
Evaluate the expression:
(5-8/2)*3+5
 Java proceeds as follows:
=> (5-4)*3+5
=> (1)*3+5
=> 3+5
=> 8
 Operations on values of the same
type produce values of that type
Example:
15/3=> 5
9/5 => 1
Note that when we divide 2 integers, the result is the integral
quotient with any remainder being ignored!
Division by ZERO
 In Math, division by zero is undefined
 In Java, if we divide a number by ZERO,
Java throws an arithmetic exception
I can’t
cope with
this!!!!
 If any exception is thrown during the
execcution of a program, the programmer
can write instructions to catch the
exception
modulo
 Useful Arithmetic operator written as %
 Has same precedence as multiplication and
divison
 % gives the remainder
Example
7%3 =>
8%0 =>
20%7 =>
1
Throws an Arithmetic Exception
6
public class ArithmeticProg
{ public static void main(String[] args)
{ int i = 10, j = 20;
System.out.println("Adding");
System.out.println(" i + j = " + (i + j));
System.out.println("Subtracting");
System.out.println(" i - j = " + (i - j));
System.out.println("Multiplying");
System.out.println(" i * j = " + (i * j));
System.out.println("Dividing");
System.out.println(" i / j = " + (i / j));
System.out.println("Modulus");
System.out.println(" i % j = " + (i % j));
}// main
//ArithmeticProg class
Increment and Decrement
Operators
++ operator adds one to the current value of an int or char.
-- operator subtracts one to the current value of an int or char.
 Neither operator works on doubles,
booleans or Strings
Example:
n++; and ++n; are equivalent to n = n+1;
n--; and --n;
are equivalent to n = n-1;
char c = ‘A’
c++; //will change the value c to ‘B’
Assignment Operators
<identifier> + = <expression>
is equivalent to:
<identifier> = <identifier>+<expression>
Example
x+= 3
x +=Y-2
is equivalent to x=x+ 3
is equivalent to x=x+(Y-2)
Assignment can also be combined with the
other four basic arithmetic operators:
-=
*=
/=
%=
 Example:
x -=Y+3
n *= 5
is equivalent to x=x-(Y+3)
is equivalent to n=n*5
Multiple assignments in one
statement:
 Operators are applied from right to
left
Example:
i=j=k=1
is equivalent to i=(j=(k=1))
Using Math Methods





Math.abs(-4)
Math.sqrt(25)
Math.pow(2, 10)
Math.max(10, 2)
Math.min(10, 2)
=> 4
=> 5
=> 1024
=> 10
=> 2
Download