150 likes | 327 Views
Arithmetic in Pascal. A Short Glance. We will learn the followings in this chapter Arithmetic operators Order of precedence Assignment statements Arithmetic functions ( in the next lesson ). Arithmetic Operators. Addition + Subtraction - (unary minus) Multiplication *
E N D
A Short Glance • We will learn the followings in this chapter • Arithmetic operators • Order of precedence • Assignment statements • Arithmetic functions ( in the next lesson )
Arithmetic Operators • Addition + • Subtraction - (unary minus) • Multiplication * • Real Division / • Integer Division div • Modulo (modulus) mod
Addition • 1 + 2 • NumA + NumB
Subtraction and Unary Minus • 45 – 20 • NumB – NumA • -20 + -NumC Unary minus
Multiplication • 10 * 5 • NumA * NumB • 2Y 2 * Y
Division • Real division • The result value is of type real • 5 / 2 2.5 • Integer division • The result value is of type integer • Round down to the nearest integer • 5 div 2 2
Modulo (Modulus) • The result is the remainder of a division operation • 9 mod 5 4 • 13 mod 3 1
Order of Precedence • Highest • - (unary minus) • High • *, /, div, mod • Low • +, -
Order of Precedence • High-precedence operations are performed first • Operators with the same precedence are performed from left to right • You could use parentheses to force the expressions within them to be performed first
Order of Precedence (examples) • 6 + 3 * 4 • 6 + 12 • 3 * 5mod 2 • 15 mod 2 • ( 10 + 20 ) / 5 • 30 / 5
Assignment Statements • Assignment means assigning a value to a variable • Syntax: • <variable> := <expression> • Please don’t use = , use :=
Accumulation • N := N + 1; • The value of N will be increased by 1 after this operation • Never write this in your Mathematics works
Mixed type assignment • Variables must be assigned values of the same type • Only one exception: • You can assign an integer value to a real variable • What will be the type of the variable after the assignment operation? • You can’t assign a real value to an integer variable
An Example program arithmetic; const Half = 0.5; var Int1, Int2, Int3 : Integer; Real1, Real2 : Real; begin Int1 := 10; Int2 := Int1 + 15; Int3 := Int2 mod Int1; writeln ( Int2 ); writeln ( Int3 ); Real1 := Int1 + Int2 * 2; Real2 := Int1 * Half; writeln ( Real1:2:2 ); writeln ( Real2:2:2 ); end.