Switch Statement In C.

 

Switch Statement In C. 

switch statement in c



Hello Programmers,

Today we will discuss most import control statement which is used in the programming world. That statement is mostly used in programming because it is simple and make the program easily readable and avoid redundancy and complexity. The statement is switch statement it is very important and mostly used statement in programming. 



Whenever you use 'nested if-else' your program will be complex and increase redundancy to avoid this type of hassle programmer choose switch statement over 'nested if-else'. 


Switch Statement select one out of several alternatives. The value of an expression in c language holds only integer or char value. In C language the expression does not hold other types of data except int or char.


Syntax:


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


The variable or expression within the parentheses following the switch keyword is used to test the condition and is referred to as the control variable. The control variable is calculated and if satisfied the case 1 then statements inside the case 1 is executed and if variable satisfied the case 2 then statement inside the case 2 is executed. If the variable value not satisfied any case that time default statement is executed. 

The break statement is used to transfer the control out of the switch structure. In switch statement the switch, case and default are reserved words or keywords.

The entire case structure following switch() should be enclosed with a pair of curly braces{}. If the case structure contains multiple statements, they need not be enclosed within a pair of curly braces.


Flowchart:


pic of flow chart in c


Program:


C program to print the day of the week according to the number of days entered.

#include <stdio.h>

int main()
{
  int n;
  printf("Enter the number of the day :");
  scanf(" %d ", &n);
  switch (n)
  {
   case 1:
      printf("Sunday");
      break;
   case 2:
      printf("Monday");
      break;
   case 3:
      printf("Tuesday");
      break;
   case 4:
      printf("Wednesday");
      break;
   case 5:
      printf("Thrusday");
      break;
   case 6:
      intf("Friday");
      break;
   case 7:
      printf("Saturday");
      break;
   default:
      printf("You entered wrong day");
      exit(0);
 }
 return 0;
}


Output:


Enter the number of the day: 5
Thursday


Explanation:


The program asks the user to enter a value which is stored in variable n. Then the program will check for the respective case and print the value of the matching case. Finally, the break statement exit switch statement.



Sharing Is Caring...

Comments :

Post a Comment