Thursday 1 November 2012

Chapter 13 - Nested Conditions( Using nested If ... else...) [Part 3 of 3]


Last thing u need to know about IF .. ELSE

The two concepts discussed here are 
  1. Nested blocks
  2. Indentation
Both of which can be emphasized with a single example, given below 


/*  
 Author : Ryan Sequeira  
 Date : 19thth October 2012  
 Title : Program to find the limits
*/  

#include<stdio.h>
#include<conio.h>


void main()
 {

  float num=0, u_lt=0, l_lt=0;
  
  clrscr();

  //prompt the user to enter the upper limit
  printf("Please enter the upper limit :");
  scanf("%f",&u_lt);

  //prompt the user to enter the lower limit
  printf("Please enter the lower limit :");
  scanf("%f",&l_lt);

  //prompt the user to enter a number
  printf("Enter a (decimal) number : ");
  scanf("%f",&num);

  //nested if else

  //number less than upper limit
  if(num <= u_lt)
    {
        //number greater than lower limit 
        if(num >= l_lt)
            printf("\n%f number is within the limit",num);

        else
            printf("\n%f number is less than the lower limit",num);
    }
  else
     printf("\n%f number is greater than the upper limit",num);


  getch();
 }


In the following example multiple if 's can be thought of as using multiple filters. 
The first filter checks if the upper limit is satisfied and only then proceeds with the inner block.
The second filter then checks the lower limit.

Using this logic you can place as many if's one inside the other. Also you can pair them with their respective else s to handle failed conditions. The general syntax for nested if else is given below.



if (condition) 
 {

    if (condition) 

           ........... 

    else

          ...........

}



The most important thing in nesting is the arrangement of the code. It is called Indentation.


Indentation:

Indentation is not a requirement of C programming language. Rather, programmers indent to better convey the structure of their programs to human readers. In particular, indentation is used to show the relationship between control flow constructs such as conditions or loops and code contained within and outside them.








The idea here is to arrange the code belonging to the along (same) vertical line .
In order to get used to this, use a tab every time you create a block i.e. after typing a brace bracket '{'.

Previous Post     Next Post

No comments:

Post a Comment