320 likes | 455 Views
TMC1414/TMC1413 Introduction To Programming. Lecture05:Arithmetic Calculation. Objectives. In this topic, you will learn about: Arithmetic calculation C Basic arithmetic operators Increment and decrement operators Compound assignment operators Type of arithmetic expressions
E N D
TMC1414/TMC1413 Introduction To Programming Lecture05:Arithmetic Calculation
Objectives In this topic, you will learn about: • Arithmetic calculation C • Basic arithmetic operators • Increment and decrement operators • Compound assignment operators • Type of arithmetic expressions • Explicit type conversions using the cast operator • Mathematical library functions • Random number generation in C
Basic Arithmetic Operators Arithmetic Calculation There are two types of arithmetic operators in C: • Unary arithmetic operators; and • Binary arithmetic operators. • Unary arithmetic operators • Require one operand • Include unary plus(+), unary minus (-), increment (++), decrement • (--) • Unary plus (+) no effect on the result • Unary minus (-) reverses the sign of the operand to which it applies (-ve value) • Example: • second = + 100; // second = second + 100 • second = - 100; //second = second - 100
Symbol Operator Name + Addition - Subtraction * Multiplication / Division % Remainder / Modulus Arithmetic Calculation • Binary arithmetic operators • Require two operands • Include +, -, *, / and % • Can be integer or floating point numbers (except modulus-must be integer) Additive operator Multiplicative operator
VALUE BEFORE EXECUTION VALUE AFTER EXECUTION No. first second third first second third Statement 100 7 ??? 100 7 107 1 third = first + second; 100 7 ??? 100 7 93 2 third = first - second; 100 7 ??? 100 7 700 3 third = first * second; 100 7 ??? 100 7 14 4 third = first / second; 100 7 ??? 100 7 2 5 third = first % second; Arithmetic Calculation Example: Let int first = 100, second = 7, third;
Arithmetic Calculation Increment & Decrement Operators C has two special operators for incrementing or decrementing a variable by 1: • ++ (increment) • -- (decrement) Instead of writing count = count + 1; We can more concisely write count++; or ++count; postfix / postincrement prefix / preincrement
Arithmetic Calculation count = count – 1; count--; or --count; postdecrement predecrement Consider: Example 1 int count = 3; printf (“%d”, count++); // output: count = 3; printf (“%d”, count); // output: count = 4; Consider: Example 2 int count = 3; printf (“%d”, ++count); // output: count = 4; printf (“%d”, count); // output: count = 4;
Arithmetic Calculation Rules for Increment and Decrement Operators • All increment and decrement operators are unary operators and they require variables as their operands. • The postincrement operator has the side effect of incrementing its operand by one, after the expression in which it appears is evaluated using the operand’s previous value. Similarly, the postdecrement operator does not change the value of the operand while the expression is being evaluated. After the postdecrement operator is applied, the value of the operand is decremented by one. • The preincrement and predecrement operators first generate their side effect; that is, they increment or decrement their operand by 1. Then, the expression in which they appear is evaluated. • The precedence and associativity of the increment and decrement operators are the same as those of unary + and unary -..
Symbol Compound Assignment Operator += Assign sum -= Assign difference *= Assign product /= Assign division %= Assign remainder Arithmetic Calculation Compound Assignment Operators To compute a value for an expression and store it in a variable, you have to use the assignment operator =. (known as simple assignment operator). C supports compound assignment operators, which are obtained by combining some operators with the simple assignment operator. count = count + first i.e. count += first equivalence
No. Value of fourth after Execution Statement 33 1 fourth += third; 7 2 fourth -= third; 260 3 fourth *= third; 1 4 fourth /= third; 7 5 fourth %= third; 6 fourth += third + 4; 37 7 fourth -= third + 4; 11 8 fourth *= third + 4; 264 9 fourth /= third + 4; 5 10 fourth %= third + 4; 11 Arithmetic Calculation Example: Assume intthird = 13, fourth = 20;
Confusing Equality (==) and Assignment (=) Operators Arithmetic Calculation • Dangerous error • Does not ordinarily cause syntax errors. • Any expression that produces a value can be used in control structures. • Nonzero values are true, zero values are false. Example: using == if (payCode == 4) printf (“You get a bonus!\n”); /*end if*/ Description: Checks payCode, if it is 4 then a bonus is awarded.
Type of Arithmetic Expressions Rules for Assigning a Type to Arithmetic Expressions that Involve int and double • If one or more of the operands in an arithmetic expression are of type double, the result of the expression is also of type double. • If all operands in an arithmetic expression are of type int, the result of the expression is also of type int. • In an arithmetic assignment expression statement, the type of the entire statement and the type of the value stored in the variable to the left of the assignment operator are the same as the type of the variable itself.
Type of Arithmetic Expressions Example Let double first = 4.7, second; intthird = 27, fourth; 1. first = first + third; Step 1: computer converts the value of third to type double (27.0) in temporary storage and computes a floating-point value for the expression. 31.7 Step 2: computer assigns this value (31.7) to the variable first. Since both variable first and the computed expression are type double, no conversion is necessary in performing the assignment operation.
Type of Arithmetic Expressions Explicit Type Conversions: The Cast Operator and Casting Once declared, the type of variable cannot be changed. However, sometimes, we may want to temporarily convert the types of the values of variables while computing expressions. Example #include<stdio.h> int main(void) { double amount, remnant; intno_of_fifties; printf(“Enter RM amount as a floating-point value:”); scanf(“%1f”, &amount); no_of_fifties = amount / 50; remnant = ((amount * 100) % 5000) / 100.0; printf(“Number of fifties: %d\n”, no_of_fifties); printf(“Remnant: %f”, remnant); return 0; } // end function main warning error
Type of Arithmetic Expressions The warning appeared on first computation part where effecting of the assignment operation, there may be possible loss of value. Description: The reason is that the variable amount is of type double and, when divided by 50, will compute to a value that is also of type double. The variable no_of_fifties is of type int, and during the assignment operation, the value computed by the expression will be converted to an integer, thus resulting in the loss of the fractional part. The error occurs because of the subexpression(amount * 100) % 5000 in the expression to the right of the assignment operator. Description: In this expression one of the operands of the remainder operator % is of type double, since the variable amount is of type double. We know that the remainder operator requires integer operands.
Type of Arithmetic Expressions Solution no_of_fifties = amount / 50; remnant = ((amount * 100) % 5000) / 100.0; Change to no_of_fifties = (int) amount / 50; remnant = ((int)(amount * 100) % 5000) / 100.0; Cast operator
Type of Arithmetic Expressions Cast Operator • It is a unary operator, and requires an expression as its operand. • It converts the type of the operand in temporary storage to the type specified by the cast operator. • The operand of the cast operator can be constant, variable, or expression. (if it is variable, the cast operator does not change the basic type of the variable itself; it change only the type of its value in temporary storage and uses this value in computing the expression in which it appears.) The operation of explicitly converting the type of an expression in temporary storage to a specified type is called casting. Form of a cast expression: (Type) Expression either int, double or char
Value after Execution No. Statement Expression first 1 (int) (first + second); 31 4.7 2 first = (int) first + second; 31.0 31.0 3 first = (int) first % second; 4.0 4.0 4 first = second % (int) first; 3.0 3.0 Type of Arithmetic Expressions Example: Assume double first = 4.7; int second = 27;
Mathematical Library Functions In C programming environments, there are two categories of mathematical functions: • Those that accept as their arguments values of type double and return values of type double • Those that accept and return only values of type int. Mathematical library functions are declared in standard header files. If you are planning to make use of them, you must have appropriate preprocessor directives in your program. The floating-point type function declarations are found in the math.h header file. #include<math.h> The integer type mathematical functions require the preprocessor directive #include<stdlib.h> To use the function, you have to use the proper function and know about the purpose, number and type of arguments and the type of values that are returned.
Function Purpose ceil(x) Returns the smallest integer larger than or equal to x. floor(x) Returns the largest integer smaller than or equal to x. abs(x) Returns the absolute value of x, where x is an integer. fabs(x) Returns the absolute value of x, where x is a floating-point value. sqrt(x) Returns the square root of x, where x >= 0. pow(x,y) Returns x raised to the y power; if x is zero, y should be positive, and if x is negative, y should be an integer. cos(x) Returns the cosine of x, where x is in radians. sin(x) Returns the sine of x, where x is in radians. tan(x) Returns the tangent of x, where x is radians. exp(x) Returns the exponential of x with the base e, where e is 2.718282. log(x) Returns the natural logarithm of x. log10(x) Returns the base-10 logarithm of x. Mathematical Library Functions
Function Call Value Returned ceil(4.2) ceil(4.0) ceil(-5,7) 5 4 -5 floor(4.2) floor(4.0) floor(-5.7) 4 4 -6 abs(-12) abs(-12.7) 12 12 fabs(-120) fabs(-120.8) 120 120.8 sqrt(2.7) sqrt(2) 1.643168 1.643168 pow(2,3) pow(2.0, -3.2) pow(0,-3) pow(-2.0, 3.2) 8 0.108819 Domain error Domain error exp(2.1) 8.16617 log(2) log10(2) 0.693147 0.30103 tan(45 * 3.141593/180) 1 Mathematical Library Functions Example:
Random Number Generation • rand function • Load <stdlib.h> • Returns "random" number between 0 and RAND_MAX (at least 32767) • i = rand(); • Pseudorandom • Preset sequence of "random" numbers • Same sequence for every function call • Scaling • To get a random number between 1 and n • 1 + ( rand() % n ) • rand() % n returns a number between 0 and n - 1 • Add 1 to make random number between 1 and n • 1 + ( rand() % 6) • number between 1 and 6
Random Number Generation 6 6 5 5 6 5 1 1 5 3 6 6 2 4 2 6 2 3 4 1
Random Number Generation Face Frequency 1 1003 2 1017 3 983 4 994 5 1004 6 999
Random Number Generation • srand function • <stdlib.h> • Takes an integer seed and jumps to that location in its "random" sequence • srand( seed ); • srand( time( NULL ) );/*load <time.h> */ • time( NULL ) • Returns the time at which the program was compiled in seconds • “Randomizes" the seed
Random Number Generation Enter seed: 67 6 1 4 6 2 1 6 1 6 4 Enter seed: 867 2 4 6 1 6 1 1 3 6 2 Enter seed: 67 6 1 4 6 2 1 6 1 6 4
References Problem Solving using C, Uckan, Yuksel, Mc Graw Hill, 1999. C How to Program, Deitel&Deitel, Prentice-Hall, 4th Edition, 2004.
Q & A • Any Question?