12. Arithmetic Operators_l
12. Arithmetic Operators_l
1
Arithmetic Operators
• Shortcut assignment
• Prefix form
• Postfix form
Arithmetic Expression
• Precedence rules
• Evaluate the expression
• Assignment operator syntax
• What is stored? example-1,example-2
2
Explicit Type Conversion
Math in C
• Simple equations
• Complex math
• Function
• Math library
• Math library examples
3
Arithmetic Meaning Examples
Operator
+ addition 5+2 is 7
5.0+2.0 is 7.0
- subtraction 5-2 is 3
5.0–2.0 is 3.0
* multiplication 5*2 is 10
5.0*2.0 is 10.0
/ division 5.0/2.0 is 2.5
5/2 is 2
% remainder 5%2 is 1
4
the result of the division operator depends on the
type of its operands
if one or both operands has a floating point type,
the result is a floating point type. Otherwise, the
result is an integer type
Examples
11 / 4 = 2.75 or 2
15 / 3 = 5
16 / 3 = 5
5
The modulus operator % can only be used
with integer type operands and always has an
integer type result
Its result is the integer type remainder of an
integer division
EXAMPLE
3%5=35%3=2 4%5=4 5%4=1
5%5=06%5=1 7%5=2 8%5=3
15 % 6 = 3 15 % 5 = 0
6
7
Prefix
operator
8
9
An expression is a valid arrangement of
variables, constants, and operators.
10
1) Brackets : Left to right, inner to outer
2) Unary, Multiplication, division, modulus:
left to right
3) Addition and subtraction : Left to right
13
float someFloat;
?
someFloat
12.0
someFloat
14
int someInt;
?
someInt
someInt
15
(int)4.8 has value 4
16
#include <stdio.h>
int main(void)
{
int total_score, num_students;
double average;
printf(“Enter sum of students’ scores> ”);
scanf(“%d”, &total_score);
printf(“Enter sum of students> ”);
scanf(“%d”, &num_students);
return(0);
17
b2 - 4ac
a+b
c+d
1
1 +x2
18
How do you do |x| ? y ? Z34 ?
C provides no operators for that !
However, we can use some ready-
made (predefined) functions to do
them.
19
First: What is a function?
A subprogram used to do a certain task. A function
has zero or more inputs ( called parameters), and
zero or one output (called return value)
We will study functions in more detail later.
20
The C math library provides a lot of useful
predefined math functions
Before you use them, remember to include the
math library in your code:
#include <math.h>
function sqrt:
y = sqrt ( x );
21
sin(x) cos(x) tan(x)
sqrt(x) pow(x,y)
22
Write a program to get the roots of a
quadratic equation, given the 3 coefficients
a, b, and c,
a x2 + b x + c = 0
b b 2 4ac b b 2 4ac
Root1= Root2=
2a 2a
disc = pow(b,2) – 4 * a * c;
root_1 = (-b + sqrt(disc)) / (2 * a);
root_2 = (-b - sqrt(disc)) / (2 * a);
23
Write a program to get the third side of a triangle
(a), given the lengths of the other two sides (b,
and c), and the angle using the formula
a2 = b2 + c2 – 2bc cos
b a
c
rad_angle = alpha * PI / 180;
a = sqrt(pow(b,2) + pow(c,2) – 2 * b * c *
cos(rad_angle);
24