CONTROL STRUCTURES PART-I (DECISION MAKING) || C Language - Computer Times

Latest

Sunday, 2 September 2018

CONTROL STRUCTURES PART-I (DECISION MAKING) || C Language

With the introduction of control structures we are going to have to introduce a new concept: 
the compound statement or block. A block is a group of statements which are separated by semicolons (;) like all C statements, but grouped together in a block enclosed in braces: { }:

{   statement1;   statement2   ;    statement3;  }
1.1  Conditional structure ( Selection ) if - :
The if the keyword is used to execute a statement or block only if a condition is fulfilled.    Its form is:
if (condition)
        statement 1 ;
If this condition is true, the statement is executed. If it is false, the statement is ignored (not executed) and the program continues right after this conditional structure. for example
if (x == 100)
      printf( "x is 100");
If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:
if (x == 1000)
{
printf( "x is=");
printf(“%d”, x);
}
Note: In case of single statement in if… the use of {} is optional.

 1.2   If- Else -:

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:
if (condition)
          statement1 ;
else
          statement2 ;
For example:
if (x == 1000)
       printf("x is 1000");
else
     printf("x is not 1000");
prints on the screen x is 1000 if indeed x has a value of 1000, but if it has not -and only if not- it prints out x is not 1000.

1.3 Else-if  - :
The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):
if (x > 0)
       printf( "x is positive");
else if (x < 0)
       printf("x is negative");
else
       printf( "x is 0");
Remember that in case we want more than a single statement to be executed, we must group them in a block by enclosing them in braces { }.

1.4  Nested if -:   
An if… or if..else.. may have another if.. Statement in its true block or in false block. It is known as  Nesting of if (placing an if inside another if).
Syntax :
if (condition1)
{
    if(condition 2)
        { 
              statement 1;
         }
    else
         {
          statement 2;
         }
  }
else
{
     if(condition 3)
       {
           statement 3;
           }
    else
       {
          statement 4;
       }
}

Computer Coaching in Jalandhar with Dinesh Sir,C,C++,Java Language, Computer Science CBSE,ICSC,State Board.



No comments:

Post a Comment