Program Control Selection

Program Control Selection


Selection 

Selection is one or more statement(s) that give one or more condition(s) and the statement(s) will be executed.
There are 3 operations in selection :
1. If
2. If - Else
3. Switch Case

  • If
The syntax is : 

if (boolean expression)
{
       statement(s);
}

if the boolean expression is TRUE, the statement(s) inside will be executed.

Example (a program to print i):

#include <stdio.h>

int main ()
{    
    int i;   
    i = 5; 

    if (i == 5)
   {          
       printf("%d\n", i);    
    }   
  
   return 0;
}

  • If - Else
The syntax is :

if (boolean expression)
{
       statement(s);
}

else
{
       statement(s);
}


Example (a program to print i):

#include <stdio.h>

int main ()
{    
    int i;    
     i =5;

    if(i == 5)
    {          
       printf("i is %d.\n", i);
    }
    else
    {
          printf("i is not %d.\n", i);
     }    

   return 0;
}

Nested-If

The syntax is :

if (boolean expression)
{
       statement(s);
       if (boolean expression)
      {
             statement(s);
       }
       else
       {
              if (boolean expression)
              {
                     statement(s);
               }
         }
}

  • Switch Case
The syntax is :

switch (expression)
{
     case (constant1) : statement(s);
                                  break;
     case (constant2) : statement(s);

                                  break;
     default : statement(s);
}


Princess Jesslyn Lorenza
2201750036

binus.ac.id
skyconnectiva.com



Comments