Switch Case Statement - C Tutorial

Switch Case Statement

C switch statement is used when you have multiple possibilities for the if statement.

The basic format of switch statement is:

Syntax

switch(variable)
{
case 1:
   //execute your code
break;
case n:
   //execute your code
break;
default:
   //execute your code
break;
}

After the end of each block it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from each and every case onwards after matching the case block.

When none of the case is evaluated to true, then default case will be executed, and break statement is not required for default statement.

Program to find number of days in a month using Switch Case

#include <stdio.h>
int main()
{
	int month;
	int days;
	
	printf("Enter the month number : ");
	scanf("%d",&month);
	
	switch(month)
	{
	    case  1:
		case  3:
		case  5:
		case  7:
		case  8:
		case 10:
		case 12:
		    printf("31 Days Month");
			break;
			
	    case 2:
			printf("28 or 29 Days Month");
		    break;
		    
		case  4:
		case  6:
		case  9:
		case 11:
				printf("30 Days Month");
			break;
		
		
		default:
				printf("You have Entered Invalid Month Number");
				
	}
	
	return 0;
	
}
Output - Program to find number of days in a month using Switch Case
Enter the month number : 3                                                                                            
31 Days Month 

Enter the month number : 6                                                                                            
30 Days Month