Arithmetic Operators
Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and division (/) operations. In addition there is the modulus operator (%) which gives the remainder left over from a division operation.
Example Program
Relational Operators
Relational operators compare operands and return 1 for true or 0 for false. The following relational operators are available
Symbol Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Example
int a=35,b=90,c;
c=a < b;
The value of c after execution of above code is 1 since the condition 35 < 90 is true
The logical operators are || for a logical or and && for a logical and and ! for logical not. The and and or operate on two boolean values of true or false. In C, an expression that evaluates to 0 is false and an expression that evaluates to non-zero is true. These operators return 1 for true or 0 for false.
The following table shows the results of applying these operators to different boolean values
Left Operation Right Result True && True True
False && True False
True && False False
False && False False
True || True True
False || True True
True || False True
False || False False
The table also shows that these operators can do what is called “lazy evaluation” or “short circuit evaluation”. The operands are evaluated from left to right. For an and operation, if the left operand is false, the right operand is not even evaluated because the result is known to be false. For an or operation, if the left operand is true the right operand is not evaluated because the result will be true.
Exampleint x=55,y=67,z=55,w;
w=(x==z)&&(x>y);
The value of w from the above code is 0 since 55==55 is true but 55>67 is false
true && false = false.
Assignment Operators
C has several assignment operators available - one simple assignment operator and several convenience assignment operators that combine arithmetic or bitwise operations with assignment. The operators are as follows:
Symbol Meaning
= Assignment
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
+= Add and assign
-= Subtract and assign
Example #1
int a,b=33;
a=b;
Example #2
int a=100,b=50;
a+=b;
In the second example a+=b means a=a+b which is evaluated as
a=100+50 which is 150.
Conditional operator (or) Ternary Operator
The conditional operator is unusual in that it takes three operands. The syntax of this operator is like this:
Condition ? Expression1 : Expression2;
You can think of the conditional operator as if it were a function that works like this:
if ( Condition ) return Expression1;
else
return Expression2;
Example
int a=101,b=50,c;
c=a>b?10:20;
In the above code the value of c will be 10 as the condition 101>50 is true.
No comments:
Post a Comment