2.arithmetic Calculation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

CSE 1101

Introduction To
Programming
Lecture03: Arithmetic
Calculation
Objectives
In this topic, you will learn about:

o Arithmetic calculation C
o Basic arithmetic operators
o Increment and decrement operators
o Compound assignment operators
o Type of arithmetic expressions
o Explicit type conversions using the cast operator
o Mathematical library functions

o Random number generation in C


2
Arithmetic Calculation
Basic Arithmetic Operators

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
3
Arithmetic Calculation
Binary arithmetic operators

-Require two operands


-Include +, -, *, / and %
-Can be integer or floating point numbers (except modulus-must be integer)

Symbol Operator Name

+ Addition
Additive operator
- Subtraction

* Multiplication

/ Division Multiplicative operator


% Remainder / Modulus

4
Arithmetic Calculation
Example:
Let
int first = 100, second = 7, third;

VALUE BEFORE EXECUTION VALUE AFTER EXECUTION


No. Statement first second third first second third

1 third = first + second; 100 7 ??? 100 7 107

2 third = first - second; 100 7 ??? 100 7 93

3 third = first * second; 100 7 ??? 100 7 700

4 third = first / second; 100 7 ??? 100 7 14

5 third = first % second; 100 7 ??? 100 7 2

5
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


postfix / postincrement
count++;

or
prefix / preincrement
++count;

6
Arithmetic Calculation
count = count – 1;
count--; postdecrement

or

--count; 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; 7
Arithmetic Calculation
Rules 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 -..
8
T
20=g is not valid
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.
Symbol Compound Assignment Operator
+= Assign sum
-= Assign difference
*= Assign product
/= Assign division
%= Assign remainder

i.e.
count += first equivalence count = count + first 18
Arithmetic Calculation
Example:
Assume
int third = 13, fourth = 20;
No. Statement Value of fourth after
1 fourth += third; Execution
33
2 fourth -= third; 7
3 fourth *= third; 260
4 fourth /= third; 1
5 fourth %= third; 7
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 19
Arithmetic Calculation
Confusing Equality (==) and Assignment (=) Operators

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.

20
Type of Arithmetic Expressions
Rules 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.

21
Type of Arithmetic Expressions
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.

22
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;
int no_of_fifties;

printf(“Enter RM amount as a floating-point value:”);


scanf(“%1f”, &amount);
warning
no_of_fifties = amount / 50; error
remnant = ((amount * 100) % 5000) / 100.0;

printf(“Number of fifties: %d\n”, no_of_fifties);


printf(“Remnant: %f”, remnant);
return 0;
} // end function main 23
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.
24
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

25
Type of Arithmetic Expressions
Cast Operator
1. 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
26
Type of Arithmetic Expressions
Example:

Assume
double first = 4.7;
int second = 27;

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

27
Mathematical Library Functions
In 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.
28
Mathematical Library Functions
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.
29
Mathematical Library Functions
Function Call Value Returned
Example:
ceil(4.2) 5
ceil(4.0) 4
ceil(-5,7) -5

floor(4.2) 4
floor(4.0) 4
floor(-5.7) -6

abs(-12) 12
abs(-12.7) 12

fabs(-120) 120
fabs(-120.8) 120.8

sqrt(2.7) 1.643168
sqrt(2) 1.643168

pow(2,3) 8
pow(2.0, -3.2) 0.108819
pow(0,-3) Domain error
pow(-2.0, 3.2) Domain error
exp(2.1) 8.16617

log(2) 0.693147
log10(2) 0.30103
tan(45 * 3.141593/180) 1 30
References

Problem Solving using C, Uckan,


Yuksel, Mc Graw Hill, 1999.

C How to Program, Deitel&Deitel,


Prentice-Hall, 4th Edition, 2004.

31
Q&A
o Any Question?

32

You might also like