Arithmetic Operators Arithmetic Operations with Variables CMSC 104 1 Arithmetic Operators Name Operator Addition Subtraction Multiplication Division Modulus CMSC 104 + * / % Example num1 + num2 initial - spent fathoms * 6 sum / count m%n 2 Modulus % The expression m % n yields the remainder after m is divided by n. Modulus is an integer operation. - Both operands MUST be integers. Examples : 17 % 5 = 2 6%3 = 0 9%2 = 1 5%8 = 5 CMSC 104 3 Integer Division If both operands of a division expression are integers, you will get an integer answer. The fractional portion is thrown away. Examples : 17 / 5 = 3 4 / 3 = 1 35 / 9 = 3 Division where one operand is a floating point number will produce a floating CMSC 104 point answer. 4 Division By Zero Division by zero is mathematically undefined. If you allow division by zero in a program, it will cause a fatal error. your program will terminate immediately and give an error message. Non-fatal errors will not cause program termination, just produce incorrect results. CMSC 104 5 Uses of Modulus Even and Odd 5 % 2 = 1 odd 4 % 2 = 0 even Take the modulus by 2 of any integer, a result of 1 means the number was odd, a result of 0 means the number was even. CMSC 104 The Euclidean GCD algorithm 6 Arithmetic Operators Rules of Operator Precedence Operator(s) () Precedence & Associativity Evaluated first. If nested innermost first. If on same level - left to right. * / % Evaluated second. If there are several, evaluated left to right + - Evaluated third. If there are several, evaluated left to right. = CMSC 104 Evaluated last, right to left. 7 Evaluation of expressions a*b+c Would multiply a * b first, then add c to the result. If we really want the sum of b and c to be multiplied by a, use parentheses to force the evaluation to be done in the order we want. a*(b+c) CMSC 104 8 Practice With Evaluating Expressions Given integer variables a, b, c, d, & e, where a = 1, b = 2, c = 3, d = 4 Evaluate the following expressions : a+b-c+d a*b/c 1+a*b%c a+d%b-c e=d+c/b-a CMSC 104 9 Good Programming Practices The required C coding standards and Indentation Styles are available on the course homepage You will be expected to conform to these standards for all programming projects in this class. Pick one of the two indentation styles shown and use it consistently. CMSC 104 10 A Sample Project We are going to write a program in class that finds the volume and surface area of a box. Write the Algorithm Use the algorithm as a guide for writing the code. CMSC 104 Project : 11 An algorithm for writing code CMSC 104 Write the algorithm Write the code using emacs Try to compile the code While there are still syntax errors Fix errors Try to compile the code Test the program Fix any semantic errors Compile the code Test the program 12