Wednesday, 8 January 2014

Programming Language C Tutorial – IV (Unary Operators, Logical Operators, Ternary Operators)

Unary Operators (++, --)
 It is also known as increment or decrement operators.
For ease understanding we have to classify it in following two types
  1. Pre – Increment : First increment in value and then proceed further e.g. ++a, ++x etc. we evaluate it by simple example
Let us assume we declare int x=10; and then assign this value to another variable int y=++x; then we will find that value of x and y is now 11.
  1. Post – Increment: First assign value and then get incremented. e.g. a++, x++ etc. we evaluate it by simple example
Let us assume we declare int x=10; and then assign this value to another variable int y=x++; then we will find that value of x is 11 and value of y is 10.
            Same things apply to decrement operator.
Logical Operator(&&, ||, !)
&&(and operator) – It evaluate the given conditions and retain true result if all conditions are satisfied otherwise false result.
Truth Table:
           
Condition1
Condition2
Condition..n
Result
True
True
True
True
True
True
False
False
True
False
True
False
False
True
True
False
False
False
False
False
For example:
            int a=10,b=20,c=5;
            int ans= a>10&&b<20&&c>5;
Here we will get false i.e. zero result (ans=0)
            int a=10,b=20,c=5;
            int ans= a>2&&b<50&&c>1;
Here we will get true i.e.1 result (ans=1)
You will try it by assuming different set of values and check all possible result.
||(or operator) – It evaluate the given conditions and return true result if only one condition is satisfied out of all conditions.
Truth Table:
           
Condition1
Condition2
Condition..n
Result
False
False
False
False
False
False
True
True
False
True
False
True
True
False
False
True
True
True
True
True
For example:
            int a=10,b=20,c=5;
            int ans= a>=10||b<20||c>5;
Here we will get true i.e. 1 result (ans=1)
            int a=10,b=20,c=5;
            int ans= a<2||b<5||c>10;
Here we will get false i.e.zero result (ans=0)
You will try it by assuming different set of values and check all possible result.
! (not operator) : It returns true if condition is false and returns false when condition is true.
Condition
Result
True
False
False
True
Conditional (Ternary) Operator
C offers a shorthand notation, which provides conditional execution of statements.
*       The conditional operator has 2 parts? and :
Let us take a example- max=num1>num2?num1:num2;
The purpose of the above statement is to assign the value of  num1 or num2, whichever is larger, to the variable max.

First the condition (num1>num2) is evaluated. If it is true, the value num1 is assigned to max, else num2 is assigned to max.

No comments:

Post a Comment