TMC1414/TMC1413 Introduction To Programming
Lecture05:Arithmetic Calculation
2
ObjectivesIn this topic, you will learn about:
oArithmetic calculation CoBasic arithmetic operatorsoIncrement and decrement operatorsoCompound assignment operators
oType of arithmetic expressionsoExplicit type conversions using the cast operator oMathematical library functions
oRandom number generation in C
3
Arithmetic Calculation
There are two types of arithmetic operators in C:
• Unary arithmetic operators; and• Binary arithmetic operators.
Basic 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
4
Arithmetic CalculationBinary 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
Arithmetic CalculationExample:
third = first + second;third = first - second;third = first * second;third = first / second;third = first % second;
1
5
3
2
4
No.
StatementVALUE BEFORE
EXECUTIONfirst second
thirdVALUE AFTER EXECUTIONfirst seco
ndthird
100 1007 7??? 107
100 100
100 100
7 7
7 7
100
100
100
100
7
7
7
7
??? 93
??? 14
???
???
2
700
Letint first = 100, second = 7, third;
6
Arithmetic CalculationIncrement & 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
7
Arithmetic Calculation
count--;
or
--count;
postdecrement
predecrement
count = count – 1;
Consider: Example 1int count = 3;
printf (“%d”, count++); // output: count = 3;printf (“%d”, count); // output: count = 4;
Consider: Example 2int count = 3;
printf (“%d”, ++count); // output: count = 4;printf (“%d”, count); // output: count = 4;
8
Arithmetic CalculationRules for Increment and Decrement Operators
1. All increment and decrement operators are unary operators and they require variables as their operands.
2. 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.
3. 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.
4. The precedence and associativity of the increment and decrement operators are the same as those of unary + and unary -..
9
Arithmetic CalculationCompound Assignment OperatorsTo 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 differenceAssign productAssign divisionAssign remainder
+=
%=
*=-=
/=
Symbol Compound Assignment Operator
i.e.count += first count = count +
firstequivalence
10
Arithmetic CalculationExample:
Assume int third = 13, fourth = 20;
fourth += third;fourth -= third;fourth *= third;fourth /= third;fourth %= third;
1
5
32
4
No.
Statement Value of fourth after Execution33
7
2607
1
6
8
10
7
9fourth %= third + 4;
fourth *= third + 4;
fourth += third + 4;
fourth /= third + 4;
fourth -= third + 4;
11
264
37
5
11
11
Arithmetic CalculationConfusing Equality (==) and Assignment (=) OperatorsDangerous 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.
12
Type of Arithmetic ExpressionsRules for Assigning a Type to Arithmetic Expressions that Involve int and double
1. 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.
2. If all operands in an arithmetic expression are of type int, the result of the expression is also of type int.
3. 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.
13
Type of Arithmetic ExpressionsExampleLet
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.7Step 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.
14
Type of Arithmetic ExpressionsExplicit Type Conversions: The Cast Operator and CastingOnce 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(“%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
warningerror
16
Type of Arithmetic ExpressionsThe 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.
17
Type of Arithmetic ExpressionsSolution
no_of_fifties = amount / 50;remnant = ((amount * 100) % 5000) / 100.0;
no_of_fifties = (int) amount / 50;remnant = ((int)(amount * 100) % 5000) / 100.0;
Change to
Cast operator
18
Type of Arithmetic ExpressionsCast Operator1. It is a unary operator, and requires an expression as its
operand.2. It converts the type of the operand in temporary storage to
the type specified by the cast operator.3. 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
19
Type of Arithmetic ExpressionsExample:
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
Expression first
4.7
31.0
4.0
3.0
20
Mathematical Library FunctionsIn C programming environments, there are two categories of mathematical functions:
1. Those that accept as their arguments values of type double and return values of type double
2. 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.
21
Mathematical Library FunctionsReturns 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 2.718282.
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.
22
Mathematical Library Functions54-5
44-6
1212
120120.8
1.6431681.643168
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 * 3.141593/180)
0.6931470.30103
80.108819
Domain errorDomain error
8.16617
1
Example:
23
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
24
Random Number Generation1 2 Shifted, scaled integers produced by 1 + rand() % 6 */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 int i; /* counter */ 10 11 /* loop 20 times */ 12 for ( i = 1; i <= 20; i++ ) { 13 14 /* pick random number from 1 to 6 and output it */ 15 printf( "%10d", 1 + ( rand() % 6 ) ); 16 17 /* if counter is divisible by 5, begin new line of output */ 18 if ( i % 5 == 0 ) { 19 printf( "\n" ); 20 } /* end if */ 21 22 } /* end for */ 23 24 return 0; /* indicates successful termination */ 25 26 } /* end main */
6 6 5 5 6 5 1 1 5 3 6 6 2 4 2 6 2 3 4 1
25
Random Number Generation1 2 Roll a six-sided die 6000 times */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 int frequency1 = 0; /* rolled 1 counter */ 10 int frequency2 = 0; /* rolled 2 counter */ 11 int frequency3 = 0; /* rolled 3 counter */ 12 int frequency4 = 0; /* rolled 4 counter */ 13 int frequency5 = 0; /* rolled 5 counter */ 14 int frequency6 = 0; /* rolled 6 counter */ 15 16 int roll; /* roll counter */ 17 int face; /* represents one roll of the die, value 1 to 6 */ 18 19 /* loop 6000 times and summarize results */ 20 for ( roll = 1; roll <= 6000; roll++ ) { 21 face = 1 + rand() % 6; /* random number from 1 to 6 */ 22
26
Random Number Generation23 /* determine face value and increment appropriate counter */ 24 switch ( face ) { 25 26 case 1: /* rolled 1 */ 27 ++frequency1; 28 break; 29 30 case 2: /* rolled 2 */ 31 ++frequency2; 32 break; 33 34 case 3: /* rolled 3 */ 35 ++frequency3; 36 break; 37 38 case 4: /* rolled 4 */ 39 ++frequency4; 40 break; 41 42 case 5: /* rolled 5 */ 43 ++frequency5; 44 break; 45
27
Random Number Generation45 46 case 6: /* rolled 6 */ 47 ++frequency6; 48 break; 49 } /* end switch */ 50 51 } /* end for */ 52 53 /* display results in tabular format */ 54 printf( "%s%13s\n", "Face", "Frequency" ); 55 printf( " 1%13d\n", frequency1 ); 56 printf( " 2%13d\n", frequency2 ); 57 printf( " 3%13d\n", frequency3 ); 58 printf( " 4%13d\n", frequency4 ); 59 printf( " 5%13d\n", frequency5 ); 60 printf( " 6%13d\n", frequency6 ); 61 62 return 0; /* indicates successful termination */ 63 64 } /* end main */
Face Frequency 1 1003 2 1017 3 983 4 994 5 1004 6 999
28
Random Number Generation
• srand function– <stdlib.h>– Takes an integer seed and jumps to that location in its
"random" sequencesrand( seed );
– srand( time( NULL ) );/*load <time.h> */• time( NULL )
– Returns the time at which the program was compiled in seconds
– “Randomizes" the seed
29
Random Number Generation1 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 int i; /* counter */ 10 unsigned seed; /* number used to seed random number generator */ 11 12 printf( "Enter seed: " ); 13 scanf( "%u", &seed ); 14 15 srand( seed ); /* seed random number generator */ 16 17 /* loop 10 times */ 18 for ( i = 1; i <= 10; i++ ) { 19 20 /* pick a random number from 1 to 6 and output it */ 21 printf( "%10d", 1 + ( rand() % 6 ) ); 22
30
Random Number Generation23 /* if counter is divisible by 5, begin a new line of output */ 24 if ( i % 5 == 0 ) { 25 printf( "\n" ); 26 } /* end if */ 27 28 } /* end for */ 29 30 return 0; /* indicates successful termination */ 31 32 } /* end main */
Enter seed: 67 6 1 4 6 2 1 6 1 6 4Enter seed: 867 2 4 6 1 6 1 1 3 6 2Enter seed: 67 6 1 4 6 2 1 6 1 6 4
31
References
Problem Solving using C, Uckan, Yuksel, Mc Graw Hill, 1999.
C How to Program, Deitel&Deitel, Prentice-Hall, 4th Edition, 2004.
32
Q & AoAny Question?