Presentation is loading. Please wait.

Presentation is loading. Please wait.

TMF1414 Introduction to Programming

Similar presentations


Presentation on theme: "TMF1414 Introduction to Programming"— Presentation transcript:

1 TMF1414 Introduction to Programming
Lecture 05 Arithmetic Calculation

2 Content Arithmetic Calculation Type of Arithmetic Expressions
Basic Arithmetic Operators Increment and decrement Operators Compound assignment Operators Type of Arithmetic Expressions Explicit type conversions using cast operator Mathematical Library Functions Random Number Generation in C

3 Arithmetic Calculation
Basic Arithmetic Operators 2 types of arithmetic Operators in C Unary Arithmetic Operators Binary 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

4 Arithmetic Calculation
Binary Arithmetic Operators Require two operands Include +, -, *, / and % Can be integer or floating point numbers (except modulus-must be integer) Addition Subtraction Multiplication Division Remainder / Modulus + % * - / Symbol Operator Name Additive operator Multiplicative operator

5 VALUE BEFORE EXECUTION
Arithmetic Calculation third = first + second; third = first - second; third = first * second; third = first / second; third = first % second; 1 5 3 2 4 No. Statement VALUE BEFORE EXECUTION first second third VALUE AFTER EXECUTION 100 7 ???

6 VALUE BEFORE EXECUTION
Arithmetic Calculation Example Let int first = 100, second = 7, third; third = first + second; third = first - second; third = first * second; third = first / second; third = first % second; 1 5 3 2 4 No. Statement VALUE BEFORE EXECUTION first second third VALUE AFTER EXECUTION 100 7 ??? 107 93 14 700

7 Arithmetic Calculation
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 form of the increment operator Prefix form of the increment operator

8 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;

9

10 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 -..

11 Compound Assignment Operator
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. Assign sum Assign difference Assign product Assign division Assign remainder += %= *= -= /= Symbol Compound Assignment Operator i.e. count += first count = count + first equivalence

12 Value of fourth after Execution
Arithmetic Calculation Example: Assume int third = 13, fourth = 20; fourth += third; fourth -= third; fourth *= third; fourth /= third; fourth %= third; 1 5 3 2 4 No. Statement Value of fourth after Execution 6 8 10 7 9 fourth %= third + 4; fourth *= third + 4; fourth += third + 4; fourth /= third + 4; fourth -= third + 4;

13 Value of fourth after Execution
Arithmetic Calculation Example: Assume int third = 13, fourth = 20; fourth += third; fourth -= third; fourth *= third; fourth /= third; fourth %= third; 1 5 3 2 4 No. Statement Value of fourth after Execution 33 7 260 6 8 10 9 fourth %= third + 4; fourth *= third + 4; fourth += third + 4; fourth /= third + 4; fourth -= third + 4; 11 264 37

14 Arithmetic Calculation
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.

15 Type of Arithmetic Expression
Example Let double first = 4.7, second; int third = 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.

16 Type of Arithmetic Expression
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; int no_of_fifties; printf(“Enter RM amount as a floating-point value:”); scanf(“%f”, &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

17 Type of Arithmetic Expression
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.

18 Type of Arithmetic Expression
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

19 Type of Arithmetic Expression
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

20 Type of Arithmetic Expression
Example Assume double first = 4.7; int second = 27; (int) (first + second); first = (int) first + second; first = (int) first % second; first = second % (int) first; 1 3 2 4 No. Statement 31 4.0 31.0 3.0 Value after Execution Output first 4.7

21 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.

22 Mathematical Library Functions
Returns the smallest integer larger than or equal to x. Returns the largest integer smaller than or equal to x. Returns the absolute value of x, where x is an integer. Returns the absolute value of x, where x is a floating-point value. Returns the square root of x, where x >= 0. ceil(x) sqrt(x) abs(x) floor(x) fabs(x) Function Purpose pow(x,y) sin(x) exp(x) log10(x) cos(x) tan(x) log(x) Returns the base-10 logarithm of x. Returns the exponential of x with the base e, where e is Returns the sine of x, where x is in radians. 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. Returns the natural logarithm of x. Returns the tangent of x, where x is radians. Returns the cosine of x, where x is in radians.

23 Mathematical Library Functions
ceil(4.2) ceil(4.0) ceil(-5,7) sqrt(2.7) sqrt(2) abs(-12) abs(-12.7) floor(4.2) floor(4.0) floor(-5.7) fabs(-120) fabs(-120.8) Function Call Value Returned pow(2,3) pow(2.0, -3.2) pow(0,-3) pow(-2.0, 3.2) log(2) log10(2) exp(2.1) tan(45 * /180) Example

24 Mathematical Library Functions
5.0 4.0 -5.0 -6.0 12.0 120.0 120.8 ceil(4.2) ceil(4.0) ceil(-5.7) sqrt(2.7) sqrt(2) abs(-12) abs(-12.7) floor(4.2) floor(4.0) floor(-5.7) fabs(-120) fabs(-120.8) Function Call Value Returned pow(2,3) pow(2.0, -3.2) pow(0,-3) pow(-2.0, 3.2) log(2) log10(2) exp(2.1) tan(45 * /180) 8.0 Domain error 1.0 Example

25 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

26 Random Number Generation (Cont.)
For example, a program that simulates coin tossing might require only 0 for “heads” and 1 for “tails.” A dice-rolling program that simulates a six-sided die would require random integers from 1 to 6. Rolling a Six-Sided Die To demonstrate rand, let’s develop a program to simulate 20 rolls of a six-sided die and print the value of each roll. The function prototype for function rand is in <stdlib.h>. We use the remainder operator (%) in conjunction with rand as follows rand() % 6 to produce integers in the range 0 to 5.

27

28 ©1992-2013 by Pearson Education, Inc. All Rights Reserved.

29 Random Number Generation (Cont.)
Rolling a Six-Sided Die 6,000,000 Times To show that these numbers occur approximately with equal likelihood, let’s simulate 6,000,000 rolls of a die with the program of Fig. 5.12. Each integer from 1 to 6 should appear approximately 1,000,000 times. As the program output shows, by scaling and shifting we’ve used the rand function to realistically simulate the rolling of a six-sided die.

30

31

32

33 Random Number Generation (Cont.)
Randomizing the Random Number Generator Executing the program of Fig. 5.11 again produces exactly the same sequence of values. How can these be random numbers? Ironically, this repeatability is an important characteristic of function rand.

34

35 Random Number Generation (Cont.)
This is called randomizing and is accomplished with the standard library function srand. Function srand takes an unsigned integer argument and seeds function rand to produce a different sequence of random numbers for each execution of the program. We demonstrate function srand in Fig. 5.13.

36 Random Number Generation (Cont.)
Function srand takes an unsigned int value as an argument. The conversion specifier %u is used to read an unsigned int value with scanf. The function prototype for srand is found in <stdlib.h>.

37 Random Number Generation
srand function <stdlib.h> Takes an integer seed and jumps to that location in its "random" sequence srand( seed );

38 Random Number Generation

39 Random Number Generation
Enter seed: 67 Enter seed: 867

40 Random Number Generation (Cont.)
Let’s run the program several times and observe the results. Notice that a different sequence of random numbers is obtained each time the program is run, provided that a different seed is supplied. To randomize without entering a seed each time, use a statement like srand( time( NULL ) ); This causes the computer to read its clock to obtain the value for the seed automatically. The function prototype for time is in <time.h>.

41 Random Number Generation

42 Random Number Generation

43 What is the result of each of the following expressions?
b) (1 + 2) * 4 / 2 c) * (4 / 2) d) 9 % 2 + 1 e) (1 + (10 – (2 + 2)))

44 Convert each of the following formulas into its C assignment equivalents: a =

45 Show the value of x after each of the following statements is performed:
x = fabs (7.5); x = floor (7.5); x = ceil (0.0); x = fabs (0.0);

46 What is the output? #include <stdio.h> c = a++; int main()
{ int a = 21; int b = 10; int c ; c = a + b; printf("Value of c is %d\n", c ); c = a - b; c = a * b; c = a / b; c = a % b; c = a++; printf("Value of c is %d\n", c ); c = a--; c = --a; printf("Value of c is %d\n", a ); }

47 What is the output ? #include<stdio.h> int main() {
int a, b, c, d; int x = 10; a=x++; printf("value of a:%d\n", a); b=++x; printf("value of b:%d\n", b); c=--x; printf("value of c:%d\n", c); d=x--; printf("value of d:%d\n", d); printf("value of x:%d\n", x); return 0; }

48 Thank You


Download ppt "TMF1414 Introduction to Programming"

Similar presentations


Ads by Google