Tuesday, September 23, 2014

Conditional or ternary operator in C

/* Biggest of two numbers using i) if else statement and ii) ternary operator */

Before going to discuss about ternary operator lets check the below program

/* biggest of two numbers *?
main()
{
   int a,b;
   printf("\n enter any two numbers");
   scanf("%d%d",&a,&b);
   if(a>b)
   {
      printf("%d is big",a);
    }
   else
   {
     printf("%d is big",b);
   }
 }

output: enter any two numbers 10 20
20 is big


In the above program we assigend a value  to 10 and b value to 20
Here 'if' is called decision making statement i.e., based on the decision either 'if' part or 'else' part will be executed.
Here 'else' part will be executed because condition is false(0). So in output we see like "20 is big"
(Note: if condition is true(1) 'if' part will be executed)

Now the same thing can be performed using tenary(condional) operator.   (?  :)



/* biggest of two numbers */
main()
{
   int a,b,big;
   printf("\n enter any two numbers");
   scanf("%d%d",&a,&b);
 
   big=(a>b)?a:b;

   printf("%d is big",big);
}

output:   enter any two numbers 10 20
 20 is big

In the above program output is printed as "20 is big"

We can divide a ternary operator in c into three parts
first part conditiona part(here a>b?)
second part positive part(true part) here a   (equivalent to if part)
third part negative part(false part) here b     (equivalent to else part)
 In the above part a is assigned a value 10 and b is assigned a value 20.
and big=(a>b)?a:b;

In evaluating this expression the compiler starts from left and move to right.
first conditional part will be evaluated i.e., a>b?  ( here condition is false)
then compiler skips the second part amd moves to third part (since condition is false, the compiler moves to thrid part) i.e., big is assigned a value to b.
So output printed is "20 is big"



NOTE: if else statement can be replaced by ternay operator.




c programming, if statments, else if statements, nested if, elsed if ladder, arrays,strings, strucutres, unions, userdefiend data types, bit wise operators, ternary operator, conditional operator, file handling in c, fseek function, ftell fucntion, rewind function, logical operators , switch statements, is ternary statement is equlivalent to if else statements,biggest of two numbers, poitner in c, switch statement in c, decision making in c, control strcutures in c. biggest of three numbers

No comments:

Post a Comment