Title: Cs operators
1Cs operators
- Binary Operators
- Unary Operators
- Order of Operator Precedence
- Associativity of Operators
- Assignment Statement and Mixed data-type
calculations - Type Casting
- Relational Operators
- The if else statement
- Logical Operators
- Conditional, Increment, Decrement, sizeof and
comma Operators
2Binary Operators
Most work in the familiar way
- / div (produces quotient) mod
(produces remainder) - Both divide
- 5 / 2 2 5 2 1
- 5.5/2 2.75 5.5 2 !!!
- NBrequires integers on both sides
3Unary Operators
- Operates on, or affects, a single value
- Unary
- Generally, you do not need to use the unary plus.
C assumes a number or variable is positive - Example a 25 //Assign a a positive 25
- Unary
- Useful if you want to negate a single number or
variable (the negative of negative is positive) - Example c -a //Assign c the negative of a
- If you want to subtract the negative of a
variable, put a space before the unary minus - Example new_temp old_temp -
-inversion_factor
4The Order of Precedence (Math Hierarchy)
What is 2 3 -2 ?
- To understand C calculations you must understand
the order of precedence - C has 47 operators and 15 precedence levels
- and / are on the same precedence level ? no
hierarchy on same level - Therefore, use Associativity rules in case more
than one operator (with the same precedence
level) appear in a calculation - Use parenthesis ( ) to override rules
5Rules
- Precedence - order of evaluation
Prefix/Postfix
6The Assignment Statements
- Uses of the assignment operator ( )
- Single assignment a 4
- Multiple assignment abcd0
- //useful for variable initialization
- Compound assignment salary salary 1000
salary 1000 //is the same as above
7Mixed data-type calculations
- You can mix data types in C, such as
- Add an integer to a double
- C converts the smaller of the two types to the
other - // Mixed Type Calculation Demo
- include ltstdio.hgt
- main()
-
- int bonus 50
- float salary 1400.50
- float total
-
- total salary bonus // bonus becomes a float
temporarily - printf(The total is .2f, total)
- return 0
8C Promotion Rules
- The C compiler uses the following rules to
promote the types if two operands do not agree in
expressions
9Implicit Conversion
- If the compiler expects one type at a position,
but another type is provided, then implicit
conversion occurs. - Conversion during assignments
- char c 'a'
- int i
- i c / i is assigned by the ascii of a
/ - Arithmetic conversion if two operands of a
binary operator are not the same type, implicit
conversion occurs - int i 5 , j 1
- float x 1.0, y
- y x / i / y 1.0 / 5.0 /
- y j / i / y 1 / 5 so y 0 /
- y (float) j / i / y 1.0 / 5 /
- / The cast operator (high precedence) performs
explicit conversion /
10Type Casting Explicit Conversion
- Most of the time, you do not have to worry about
Cs automatic conversion of data types. - Problems can occur if you mix unsigned variables
with other data types - You can override Cs default conversions by
specifying your own temporary type change using
the format - (data type) expression
- (data type) can be any valid C data type and
expression is any variable, constant or a
combination of both, e.g. - This code type casts the integer variable age
into a double floating-point variable
temporarily, so it can be multiplied by the
double floating-point factor - age_factor (double)age factor
11Type Casting
Instead of letting C perform the conversion, you
can type cast (or explicitly convert) all mixed
expressions daily_interest_rate interest_rate/
(float)365 daily_interest_rate principle
daily_interest_rate (float)days
- //calculate Interest on a Loan
- include ltstdio.hgt
- main()
-
- int days 45 //days since loan origination
- float principle 3500.00 //original loan
amount - float interest_rate 0.155 //Annual interest
rate - float daily_interest_rate //Daily interest
rate - daily_interest_rate interest_rate/365
//compute float value -
- //Because days is integer, it will be converted
to float next - daily_interest_rate principle
daily_interest_rate days -
- principle daily_interest_rate //update
principle with interest -
- printf(The balance you owe is .2f,
principle) - return 0
12Relational Operators
- Their task is to compare data
- Assume your program has the following
declarations - int a 5
- int b 10
- int c 15
- int d 5
These statements are False a ! d b gt c c lt a A
FALSE relational result evaluates to 0
These statements are True a d b lt c b gt a A
TRUE relational result evaluates to 1
13The if Statement
- You incorporate relational Operators in C
programs with decision statements such as the if
statement. It tests a relationship (using the
operator) and based on the tests result makes a
decision on which statement to execute next - if (condition)
- block of 1 or more C statements
- The (condition) includes any relational
comparison enclosed in parenthesis DO NOT put a
semi colon at the end of relational test
- The block of 1 or more C statements (or body of
the if statement) is any C statement(s) enclosed
in braces. - If block consists of a single C statement, the
braces are optional (it is good programming
practice to always keep them) - Each statement in block is terminated by a semi
colon - block or body of if is usually indented to
improve readability!
14Expressions as the condition
- include ltstdio.hgt
- main()
-
- int age 21 // declares age and assign value
21 -
- if (age 85)
- printf(You lived through a lot!)
- // Rest of Program
- C interprets any non-zero value as TRUE and zero
always as - FALSE
- Confusing Equality operator () with Assignment
() is a common error in C programs The
nonzero test makes it difficult to find. C
designers intended that you take advantage of
this feature, for instance, you can perform and
assignment and test it on the same line
if ((coursework exam ) gt 60,
students_passed) printf(Passed)
15The Worlds Last C Bug!
- This is not a syntax error, so the program can
execute -
- status check_radar ( )
- if (status 1)
- launch_missiles ( )
-
- //Rest of program
16Example of if statement Usage
- //Program to print the square of an input value
less than 180 - include ltstdio.hgt
- main()
-
- int num, square
- printf(What number you want squared?)
- scanf(d, num)
- if (num lt 180)
- square num num
- printf(The square of d is d\n, num,
square) -
- if (num gt 180)
- printf(c, \x07) // Beep
- printf(Square not allowed for numbers greater
than 180) - printf(Run this program again and use a
smaller number) -
- printf(Thanks for using my program)
- return 0
17The else statement
- Never appears without an if statement
- if (condition)
- block of 1 or more C statements
- else
- block of 1 or more C statements
- If condition is False, the block following the
else executes instead -
- if (num lt 180)
- square num num
- printf(The square of d is d\n, num,
square) -
- else
- printf(c, \x07) // Beep
- printf(Square not allowed for numbers greater
than 180) - printf(Run this program again and use a
smaller number) -
18Logical Operators
- Used to combine more than one relational test
into a compound relational test - The first two never appear by themselves (always
go between relational tests) - Truth Tables show you how to achieve results from
an if statement that uses these operators
19Logical Operators
- Do not use ! Or your programs will not be
!(unclear) - Use ! Sparingly,always look for the reverse logic
- if ((a lt b) (c gt d))
- printf(Results are invalid)
- a must be less that b and AT THE SAME TIME c is
greater than d for the printf statement to
execute - if (!(sales lt 1000)
- bonus 500
- sales must be greater than 100 for the printf
statement to execute
- The ! Operator is helpful especially for testing
end of file or keyboard data entry
20Cs Logical Efficiency
- C attempts to be more efficient than other
languages, if multiple relational tests are
combined into one logical expression using a
logical operator C does not always interpret the
whole expression, e.g. - if (( 5 gt 4) (2 gt 1))
- C looks only at the first expression, if it true
it will not bother with the second - Or if (( 5 lt 4) (2 gt 1))
- C looks only at the first expression, if it false
it will not bother with the second - Most of the time this doesnt pose a problem, but
the following expression may not fulfill your
expectations - if((medical Y)(((coursework exam ) gt
60), students_passed)) printf(Passed) - Your assignment students_passed may never
execute!
21The sizeof Operator
- Is a unary operator (operates on a single value)
- Produces a result that represent the size in
bytes or the data specified - Format
- sizeof data
- e.g.
- int a 5
- sizeof a //produces 4
- or
- sizeof (data type)
- e.g. sizeof (char) //produces 1
22The comma Operator
- You have already seen how this operator works, it
doesnt operate on data but allows more that one
expression to appear on the same line, e.g. - int i 10, j 20
- Is used to separate arguments in Input/Output
function calls, e.g. - printf(d .2f c, aninteger, afloat, achar)
- The comma allows some interesting statements,
e.g. - i 10 //i is assigned the value 10
- j (i 12, i 8) //i is assigned 12 added to
8 produces 20
23The conditional Operator
- Cs only ternary operator, i.e. requires three
operands (as opposed to the unarys single and
the binarys double operand requirement) - Used to replace simple if-else logic using the
format - conditional_expression ? expression1
expression2 - The conditional_expression is any expression that
results in a True (nonzero) or false (zero)
answer. - If True expression1 executes, otherwise
expression2 executes - Example
- (sales gt 1000) ? Bonus 500 Bonus 0
24The conditional Operator
- if (a gt b)
- ans 10
- else
- ans 25
- Rewritten using the conditional operator
- (a gt b) ? (ans 10) (ans 25)
- //Always use parenthesis around conditions and
expressions - Because each C expression has a value, you can
even make this statement more compact - ans (a gt b) ? (10) (25)
25The increment and decrement Operators
- Can add or subtract 1 to or from variables
- for Increment for Decrement
- i i 1 //same as i i i - 1 //same as
-i - They can go on either side of the modified
variable
- prefix form variable is changed before
expression is evaluated - postfix form variable is changed after
expression is evaluated
26The increment and decrement Operators
- Whether you use prefix or postfix does not matter
if you are incrementing or decrementing single
variables on lines by themselves, e.g. - a
- if a is equal to 5, after executing this
statement, the value of a is 6 - But if you use a in this context
- b a 1
- This statement will first increment the value of
a, subtract 1 - then assign the result to b
- Suppose you had b a 1
- This statement will use the original value of a,
subtract 1, - then assign the result to b
27The increment and decrement Operators
Output Postfix increment 4 Now a is 5 Prefix
increment 6 Now a is 6 Postfix decrement 5
Now b is 4 Prefix decrement 3 Now b is 3
- include ltstdio.hgt
- int main ()
- int a4, b5, result
-
- printf("Postfix increment d\n", a)
- printf("Now a is d\n", a)
- printf("Prefix increment d\n", a)
- printf("Now a is d\n", a)
- printf("Postfix decrement d\n", b--)
- printf("Now b is d\n", b)
- printf("Prefix decrement d\n", --b)
- printf("Now b is d\n", b)
- return 0