C If-Else

Conditions are checked for truth or falsity through If-Else construct in C. The basic form of this statement is as follows:

if(condition)
 statement1;
else
 statement2;


Here compiler decides to execute statement1 if the 1st condition is true. If it is false, then the 2nd statement will be executed.

We can change this form a bit. We can say :-

if(condition is true) statement1;
if(condition is false) statement2;


Here we are not including the <else> part. The condition placed between those braces has to be satisfied or fulfilled or true for executing corresponding statements. If a program has one
<if> and one corresponding <else> part, it is obvious that the control will always come to any one of them, either to <if> part or to <else> part. But if a program has two <if>s, the control will come to both of them. We will discuss it later. One example of if-else is shown below.

Example 0.1:
main()
{

 int i=8;
 if(i>=6)
  printf(" i is equal to or greater than six");
 else
  printf(" i is lesser than six");
}


Output: i is equal to or greater than six

Here the
<if> has a condition that is true. Hence the 1st statement gets executed. Had the condition been false, the second statement would have been executed. Another example...

Example 0.2:
main()
{

 int i=8,j=24;
 if(i==j)
   printf(" i is equal to j");
 else
   printf(" i is greater/lesser than j");
}

 

Output: i is greater/lesser than j

As the condition isn't true, control will move to the
<else> part and print the message. Another example..

Example 1.1:
main()
{

 int i=2;
 if(i==1) printf("\n this is one");
 if(i==2) printf("\n this is two");
 if(i==3) printf("\n this is three");
}
 


Output:  this is two

Here the first & last
<if> checking get false values. (i==1) and (i==3) get evaluated to be false, so as the third condition is true, only the 2nd statement gets executed. The same problem/program can be re-written including a <else> part to give the same output. It'll be looking like as follows..

if(i==1) statement1;
else if(i==2) statement2;
else if(i==3) statement3;

Both the programs are valid in syntax and give same result. The difference is that, in the previous program all
<if>s will be checked whereas in the last program the first two <if>s would be checked, and as the second condition is true the control does not need to go for & check the second <else> part. Hence the second program is a little faster than previous.

Another thing to understand properly. Every condition in
<if>,should be evaluated ultimately into true or false value. Computer gets 0(zero) for a  false and non-zero for a true. This non-zero could be any value 2,234,-674 etc.

In the above program, when the condition (i==2) is true, the machine gets a value that is a non-zero, so corresponding statements get executed. In case of (i==1), it gets a zero value because the condition is false, so it does not execute the corresponding printf() statement.

We can write multiple statements instead of one, using two braces inside the if block. Example.

Example 2.1:
main()
{

 int i=3;
 if(i==4) { printf("\n heal the world");
            printf("\n make it a better place");
            printf("\n for you and for me....");
          }
}

 

Output:  No output

This program first compares the value of i with 4.As this condition does not get satisfied, hence no statements will be executed. If the condition was true, all the three statements would have been executed. Here the two additional braces { } are necessary. Had not we used these braces, things would have been a bit different. The program would look more like this...

Example 2.2:
main()
{

  int i=3;
  if(i==4)  printf("\n heal the world");
  printf("\n make it a better place");
  printf("\n for you and for me....");
}


Output: 
make it a better place
for you and for me....

Here the computer first checks the 1st condition. Since it is false the corresponding statement printf("\n  heal the world");  will not be executed. But the rest two statements are beyond the reach of
<if>. So they accordingly gets executed. There is some more things in the if-else ladder. We'll take the above example 1.1 once again.

Example 1.2 :
main()

{
int i=1;
if(i==1) printf("\n this is one");
if(i==2) printf("\n this is two");
if(i==3) printf("\n this is three");
}


Here three checking is made but ultimately only 1st statement gets executed as the rest conditions are not true. But I'm re-writing this again.

Example 1.3:
main()

{
int i=1;
if(i==1){ printf("\n this is one");i=2; }
if(i==2){ printf("\n this is two");i=3; }
if(i==3) printf("\n this is three");
}


In the example 1.3 , checking is made three times and three statements get executed. Why? As the 1st condition (i==1) is true, the first printf() works, and i gets a new value 2. Next time (i==2) condition gets satisfied, hence 2nd printf() works and i gets 3 as a value and so on. That means, if your program has multiple
<if>s without <else>,control will come to all <if>s. But if you have an <else> part in your program, then the control will come to only any one of them.

Now consider the same example including the
<else> part.

Example 1.4:
main()
{

 int i=1;
 if(i==1){printf("\n this is one");i=2;}
 else
 if(i==2){printf("\n this is two");i=3;}
 else
 if(i==3)printf("\n this is three");
}


Now what will happen? Here, we are using
<else>. If the first condition is satisfied then machine thinks there is no need to move on to next <else> statement. Hence the very first message "this is one" is  printed on the screen, i gets a new value 2 and the program terminates.

Example 3.1:
main()
{

  int i=9;
  if(i) printf("\n hi");
}


This is a valid program. As i has a non-zero value, the condition in
<if> is true, hence the printf() flashes "hi" on the screen. Had the value of i been 0(zero), the condition would have been false and hence no statement was to get executed. I am giving another example.

Example 3.2:
main()
{
 

 if(1)
   printf("\n india is great");
}


Here, as the
<if> is given a non-zero value 1, so the condition always becomes true and the printf statement gets executed. If we replace this 1 with -4,999 or 4, things would be same. Since, any condition is ultimately evaluated into zero or nonzero value, no matter whether we give a properly formatted condition or not. similarly in statement,

if(0) printf("\n this is boring lecture");

the
<if> is getting a zero value, so the condition becomes a false, hence no statement will be executed.

Another different example:
 

Example 3.2:
main()
{

  if(3-2) printf("\n this is bad");
  if(3-2+2-3) printf("\n this is good");
}

 

The 1st <if> condition evaluates to be true, hence 1st statement gets executed while the 2nd <if> evaluates to be 0, hence nothing gets printed on screen.

A few more examples:

if(123
>123) printf("\n false");
/* Nothing is printed */

if(123>=123) printf("\n true");
/* true is printed */

if(123
<=12+2344) printf("\n true");
/* true is printed */


Another tricky example....

if('A') printf("A");       /* valid statement*/
if('a') printf("a");       /* valid statement*/


Here the first condition has 'A' which has an ASCII value of 65 (a non-zero value). So the condition is true and first printf() function prints message. Similarly the 2nd condition is also true, so the 2nd printf() also works.

if('X'
<'x') printf(" X is smaller than x");

Actually 'X' (capital X) has ASCII 88 and 'x' (small letter) has something greater than that(119). So as (86
<119) is always true, the statement following it gets executed.

if('Z'+'F'+'b'-98/2*7-'Q'/'d') printf(" what a condition!");

We need to evaluate the expression 'Z'+'F'+'b'-98/2*7-'Q'/'d' taking corresponding ASCII values of character constants used in it. Finally if it's a non-zero value the corresponding  printf() will definitely work out.

Example 3.3:
main()
{

 int A=12, B='B';
 if(A
< 'A') printf("\n how nice girl she is");
 if(B == 'B')printf("\n B=%d",B);
}


The first condition is (12
<65). As it is true, the printf() function works. In second <if>, the condition is also True and so the output is B=98.

Now one common error is putting a '=' instead of '==' within the
<if>. Follow the example.

Example 3.4:
main()
{
 

  int a=12;
  if(a=12) printf("\n good morning to all of you"); 
  /* A valid statement &
<if> has assignment operator */
}


Notice that,
<if> has assignment (=) operator, not a relational operator(==). As a NONZERO value is being assigned, the condition would be true always, hence the following printf() will show the message. But if we write it in this way ::

if(a=0) printf("\n good morning to all of you");

A zero is being assigned, so the condition will be a false one, hence no output.

Example 3.5:
main()
{
 

  int a = 14;
  if (a = (10 + 5))  a++;
    printf("\n a=%d",a);
}

output will be: 16.

Explanation:
Initially a had a value of  14. In the if  statement, notice that, there is an assignment job, and as 15 (a Non-Zero value) is  being assigned to variable "a", the condition will always be true. So, a++; statement will work  out and increase the value of  a to 16. So the last printf() will print 16 on screen.

Example 3.6:
main()
{
 

  int a = 14,b=14;
  if (a++ == b++) 

  {  
    a++; b++; a = a++ +  a++ + a++;
  }
  printf("\n a=%d ,b=%d ",a,b);
}

 

The output will be : a=51, b=16.

Explanation: At first, (a==b) condition is checked, then both are incremented to 15. As the condition is true, the control goes inside the curly brace. Next, a & b, both are incremented again to have value of 16. Now a = a++ + a++ + a++ ; is evaluated. Result of this statement would vary in compiler implementation, however on  Borland Turbo C, a's current value (16) is taken for the summation. 16+16+16 gives 48, so now variable "a" gets a new value of 48 and then the value of "a" is raised 3 times to 51.

Now some erroneous statements for you, which we should not try as they would never work out.

if( if(i==4) ) printf("hi");
/* Notice that it has 2 nested
<if>s causing Syntax error */

if(2i+4) printf("hi");
/* In algebra 2i means 2*i,. In C, it's not allowed & */


if() printf(" hi");
/* leaving the condition space blank is Erroneous */

if(23++) printf"hi"); 
/* 23++ is not possible */


Example 3.7:
main()
{

 int i=2;
 if(!(i==2)) printf("\n good morning");
 if(!(i==90)) printf("\n my goodness");
 if(!i) printf("\n bad morning");
 if(!i+45) printf("\n good day");
 if(!i+0) printf("\n bad day");
 if(!i+!i) printf("\n good night");
 if(!i++) printf("\n bad night");           
 if(++!i) printf("\n good afternoon");      

 /* erroneous statement */
 if(++!i--) printf("\n Noon");

 /* erroneous statement too*/
 if(!0) printf("\n not zero -> non zero");
 if(!1111) printf("\n zero");
 if(i++) printf("\n feel good");
}


And here are the outputs....
my goodness
good day
not zero -> non-zero
feel good


Now we'll discuss every statement in details.
1. if(!(i==2))  is as  if(!TRUE)  because i==2 is TRUE. And  !TRUE is  FALSE.
    So it becomes if(FALSE), so "good morning" is NOT printed.
2. if(!(i==90)) is as  if(!FALSE)  because i==90 is FALSE. And !FALSE is  TRUE.
    So  it becomes if(TRUE), so "my goodness" is printed.
3. if(!i) is as if(!TRUE) because i(NON-ZERO) is TRUE. And !TRUE is FALSE.
    So it becomes if(FALSE), so "bad morning" is NOT printed.
4. if(!i+45) is as if(!TRUE+45)  because i is TRUE. And !TRUE is FALSE.
    Hence if(FALSE+45) becomes if(0+45) as TRUE, so "good day" is printed.
5. !i means !TRUE or 0,hence !i+0 means 0+0 i.e 0, so condition becomes FALSE
6. !i+!i = 0+0 = 0, if(FALSE) makes no printf() statement execution.
7. !i++ is same as !(i++) because according to operator precedence table, ++ 
   gets higher priority than NOT operator. Now !(i++) becomes !(3). Variable i is
   incremented to 3. Again, !3 or !NON-ZERO evaluates to be ZERO, and
   finally if(ZERO) shows no output.
8. This is an erroneous statement. It is same as ++(!NON-ZERO), i.e ++(ZERO)=> ++0.
9. Same as above, ++(ZERO)-- is ++0-- is invalid. hence the error.
10. !0 means NOT Zero i.e non-zero, condition is true. So output can be expected.
11. !1111 means NOT Non-Zero i.e Zero, hence the condition is false and no output.
12. Increments i which is a non-zero. Hence the output is shown.

Now more NOTs (!) to come...
Two consecutive NOTs can be eliminated according to our concept. For example..

1) !!ZERO  is  !(!ZERO)  is  !(NON-ZERO) is ZERO, So, !!ZERO is same as ZERO.
2) !!!!FALSE is !(!(!(!FALSE))) is !(!(!TRUE)) is !(!FALSE) is !TRUE is FALSE
3) if(!!!!!!!123) means if(!123) as 6 NOTs were eliminated.

Another NOT(!) example.

Example 3.8:

main()
{

  int x=100;
  if(!!x)
    printf("\n x=%d", !x);
  else
    printf("\n x=%d", x);
}


Output is: x=0.

Explanation: In the if  statement, the condition has two NOT(!), and we said earlier that 2 consecutive NOTs (!) can be eliminated. So it ultimately becomes if(x) and as x has a true value of 100, the condition is true. So the control goes to the first printf() and (!x)'s value 0 gets printed.

Now some different if statements....

Example 3.9:
main()
{

 int i=8;
 if((i==8)?8:0) printf("\n hi");
 if("hi!how are you") printf("\n hi! how are you");
 if("HI","HOW","ARE","YOU") printf("\n it's good for nothing");
 if(&i) printf("\n hi");
}


1. (i==8)?8:0 will give 8, so ultimately it becomes if(8) printf("hi"); Hence "hi" is printed on screen.
2. Second example is peculiar and is good for nothing. It has no use at all but it's a valid statement. The condition is a string or series of characters. if(string) is evaluated to if(address of that string) which will always give an TRUE value as memory addresses are numbers.
3. Same thing for the third statement.
4. In the fourth statement, &i means address of variable i and address is always a positive number giving a TRUE value.

We use if-else ladder for mainly comparison purposes. We can even compare two Variables whose data types are different. For example..

main()
{

  char a='A';
  float b=65;
  if(a==b) printf("\n equal "); 

  else printf("\n different ");
}

 

Here a is  an char, b is a float data type. We compared them and as both contain 65, "equal" will be printed.

Some weird Conditions ::

if (123,234,0) printf("\n we are weird");
if (0,23,34,45+56*56) printf("\n all are useless conditions");
if(  i==5? "Yes":"No" ) printf("\n hi");
if(  i==5? "Yes": 0 ) printf("\n hi");
if ( printf("") ) printf("fgh");


The printf() function returns number of bytes it outputted. Hence if( printf("") ) would evaluate to be false.
In case of Comma separated values as in if(123, 234, 0 ) the last value is taken to make it if( 0 ).

No comments: