The switch-case statements

The switch statement provides an alternative to the if-else chain for cases that compare the value of an integer expression to a specific value. The general form of a switch statement is switch is

switch(expression)
{
   case value_1:
     statement1;
   break;
   case value_2:
     statement 2;
   break;
     case value_n:
   statement n;
     break;
   default:
      statement;
    break;
}

The switch statement uses four new keywords switch case, default and break. The keyword switch identifies the start of the Switch statement. The expression in parantheses following this word is evaluated and the result of the expression is compared to various alternative values contained within the switch statement. The keyword cane is used to identify or label individual values that are compared to the value of the switch expression. The switch expression's value is compared to each of these case values in the order that these values are listed until a match is found. When a match occurs, execution begins with the statement immediately following the match. Any number of case labels may be contained within a switch statement in any order.

The word default is optional and operates like the last else in an if-else chain. If the value of the expression does not match any of the case values, program execution begins with the statement following the word default. The break statement signals the end of the particular case and causes execution of the switch statement to be terminated. At the end of every case, there should be a break statement. Otherwise. it will result in causing the program execution to continue into the next case whenever the case gets executed.

The example below illustrates the usage of the switch statement.

Example 2.5

The program below checks whether the entered character is a vowel or not using the switch-case construct.

#include <stdio.h> 
int main()
{
    char choice ; 
    printf ("Enter any character"); 
    scanf ( "%c",&choice);
    switch(choice)
    {
        case 'a': 
           printf ( "The character is a vowel") ; 
       break;
       case 'e':
           printf ("The character is e vowel"); 
       break;
       case 'i': 
          printf ("The character is i vowel");
       break;
       case 'o':
          printf("The character is o vowel");
      break;
      case 'u':
           printf ("The character is u vowel");
      break; 
      default: 
         printf ("The character is not a vowel");
      }
}

Iterative Control Structure

The C language has the ability to repeat the same calculation or sequence of over and over instructions again, each time using different data. The iterative structure consists of an entry point that includes initialization of variable, a loop and an exit point. The continuation condition, a loop body statements that permit C language to perform iteration are while, for and do-while Statements.