Switch statement



Read any month number and display Month name in word
using of switch statement



Hello friends, in this blog we see the use of switch statement. Switch statement is also known as switch case because in this cases are executed according to user choices. This is multiple or multiway branching statement. Switch statement checks whether an expression matches any one of the constant value or not if not the control is transfer to the next statement. If none of any case matches the control is transfer to default condition.

Syntax:
                   switch(expression)
                         {case 1:
           statement 1;
           break;
                                  case 2:
           statement 2;
           break;
                                 case 3:
          statement 3;
          break;
.
.
.

       case n:
          statement n;
           break;
                                  default:
           statement;
                                 }
C program for read any month number and display Month name in word

#include<stdio.h>
#include<conio.h>
void main()
{
int n; //declar integer n
clrscr(); //to clear output screen
printf("Enter the month No:-> ");
scanf("%d",&n);  //store the input in n variable
   switch(n) //pass the value of n in switch case
   {
          case 1:
          printf("January\n");//if n=1 the Jaunary will print
                 break;
                 //to break or stop the execution and pointer goes to next step
          case 2:
          printf("February\n");
                 break;
          case 3:
          printf("March\n");
                 break;
          case 4:
          printf("April\n");
                 break;
          case 5:
          printf("MAy\n");
                 break;
          case 6:
          printf("June\n");
                 break;
          case 7:
          printf("July\n");
                 break;
          case 8:
          printf("August\n");
                 break;
          case 9:
          printf("September\n");
                 break;
          case 10:
          printf("October\n");
                 break;
          case 11:
          printf("November\n");
                 break;
          case 12:
          printf("December\n");
                 break;
          default:
          //if all 12 conditions are returns false then default will execute
          printf("Invalid Month number\nPlease try again ....\n");
                 break;
      }
getch();
}
________________________________________________________

Output:
Enter the month No:0
Invalid Month number
Please try again ....

Enter the month No:7
July

Enter the month No:3
March

Enter the month No:1
January

Enter the month No:9
September

Enter the month No:13
Invalid Month number
Please try again ....


Switch statement Switch statement Reviewed by Amit Waghmare on August 19, 2019 Rating: 5

No comments: