Professional Documents
Culture Documents
INTRODUCTION TO
PROGRAMMING
Assignment Operator
Arithmetic Calculation
Basic Arithmetic Operators
Increment and decrement Operators
Compound assignment Operators
6
UNARY 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
7
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
8
BINARY ARITHMETIC OPERATORS
Assume
int first = 100, second = 7, third;
VALUE BEFORE EXECUTION VALUE AFTER EXECUTION
Assume
int first = 100, second = 7, third;
VALUE BEFORE EXECUTION VALUE AFTER EXECUTION
count = count + 1;
or
11
INCREMENT & DECREMENT
OPERATORS
count = count – 1;
count--; //postdecrement
or
--count; //predecrement
Consider: Example 1
int count = 3;
14
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.
2 fourth -= third;
3 fourth *= third;
4 fourth /= third;
5 fourth %= third;
6 fourth += third + 4;
7 fourth -= third + 4;
8 fourth *= third + 4;
9 fourth /= third + 4;
10 fourth %= third + 4;
COMPOUND ASSIGNMENT
OPERATORS
Example: Assume
int third = 13, fourth = 20;
Type casting is a way to convert a variable from one data type to another
data type.
Type conversions can be implicit which is performed by the compiler
automatically, or it can be specified explicitly using cast operator.
It is considered good programming practice to use the cast operator
whenever type conversions are necessary.
It is best practice to convert lower data type to higher data type to avoid data
loss.
Data will be truncated when the higher data type is converted to lower.
For example, if a double is converted to int, data which is presented after
the decimal point will be lost/truncated.
C-TYPE CASTING –
IMPLICIT
CONVERSION
The usual arithmetic conversions are implicitly
performed to cast their values in a common type
C uses the rule that in all expressions except assignments
EXAMPLE
C-TYPE CASTING: EXPLICIT
TYPECASTING
Example
Assume double first = 4.7;
int second = 27;
a) 1 + 2 * 4 / 2
b) (1 + 2) * 4 / 2
c) 1 + 2 * (4 / 2)
d) 9 % 2 + 1
e) (1 + (10 – (2 + 2)))
EXERCISE 2