SFTW120-LectureNotes-03

# SFTW120-LectureNotes-03 - SFTW120 Programming Science...

This preview shows pages 1–4. Sign up to view the full content.

1 SFTW120 Programming Science Lecture Notes 3: C: Arithmetic (Textbook Chapter 2) © Robert P. Biuk-Aghai SFTW120 - Programming Science 2 Lecture Notes 3 Arithmetic operators s C has 5 arithmetic operators for integers, 4 for real numbers: Example Meaning Operator 5 % 2 = 1 remainder (for integers only) % 5 / 2 = 2 5.0 / 2.0 = 2.5 division / 5 * 2 = 10 5.0 * 2.0 = 10.0 multiplication * 5 – 2 = 3 5.0 – 2.0 = 3.0 subtraction - 5 + 2 = 7 5.0 + 2.0 = 7.0 addition +

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 SFTW120 - Programming Science 3 Lecture Notes 3 Division and remainder s Result of division depends on data type of operands: b integer / integer produces an integer result (fractional part is cut off); e.g. 5 / 2 = 2 b real / real produces a real result (including fractional part); e.g. 5.0 / 2.0 = 2.5 s For integer operations, the remainder operator ( % ) (also called modulo ) gives the integer remainder of the division of two integers, e.g. 5 % 2 = 1 (because 5 / 2 = 2 with remainder 1) SFTW120 - Programming Science 4 Lecture Notes 3 Division and remainder For any positive integers m , n : s m % n < n Example: b m = 5, n = 1. .5 b 5 % 1 = 0 b 5 % 2 = 1 b 5 % 3 = 2 b 5 % 4 = 1 b 5 % 5 = 0 s m = ( m / n ) * n + ( m % n ) Example: b m = 5, n = 2 b 5 = (5 / 2) * 2 + (5 % 2) = (2) * 2 + (1) = 5
3 SFTW120 - Programming Science 5 Lecture Notes 3 Data type of expressions s The type of an expression depends only on the type of its operands: b If all operands are int : result of the expression is int (e.g. result of 3 + 4 is int ) b If all operands are double : result of the expression is double (e.g. result of 3.0 + 4.0 is double ) b If operands are of different types ( int and double ): result of the expression is double (e.g. 3 + 4.0 is double ) s If the operands are of different type (both int and double ): mixed-type expression SFTW120 - Programming Science 6 Lecture Notes 3 Mixed-type assignments In assignment statements such as: x = y / z; the result depends on the data types of both sides of the assignment: s The expression on the right-hand side is evaluated

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 05/04/2011 for the course SFST 120 taught by Professor Dr.robert during the Spring '11 term at University of Macau.

### Page1 / 9

SFTW120-LectureNotes-03 - SFTW120 Programming Science...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online