Login
Login

Conditional/Control Statement : Switch Case

Spread the love

Last Updated on July 12, 2021 by Rahul

‘Welcome in Study Learner
Today i will teach you about conditional statement(switch case) in C Language.

Conditional/Control Statement : Switch Case :-

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax:-

switch(expression)
{
case constant-expression 1:
statement(t);
break;

case constant-expression 2:
statement(t);
break;

case constant-expression 3:
statement(t);
break;

default:
statement(t);

}

Program:-

#include<stdio.h>
int main()
{
	int i;
	printf("Enter a number:");
	scanf("%d", &i);
	switch(i)
	{
		case 1:
			printf("Monday");
			break;
		case 2:
			printf("Tuesday");
			break;
		case 3:
			printf("Wednesday");
			break;
		case 4:
			printf("Thursday");
			break;
		case 5:
			printf("Friday");
			break;
		case 6:
			printf("Saturday");
			break;
		case 7:
			printf("Sunday");
			break;
		default:
			printf("Enter between 1-7");
			break;
	}
}

Output:-

Output

How will work the program?

. If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant-expression 3, statements after case constant-expression 3 are executed until break is encountered.
. If there is no match, the default statements are executed.

If we do not use break, all statements after the matching label are executed.
By the way, the default clause inside the switch statement is optional.

create a program for month name of year?

Program:-
#include<stdio.h>
int main()
{
	int i;
	printf("Enter month number:");
	scanf("%d", &i);
	switch(i)
	{
		case 1:
			printf("January");
			break;
		case 2:
			printf("February");
			break;
		case 3:
			printf("March");
			break;
		case 4:
			printf("April");
			break;
		case 5:
			printf("May");
			break;
		case 6:
			printf("June");
			break;
		case 7:
			printf("July");
			break;
		case 8:
			printf("August");
			break;
		case 9:
			printf("September");
			break;
		case 10:
			printf("October");
			break;
		case 11:
			printf("November");
			break;
		case 12:
			printf("December");
			break;
		default:
			printf("Enter between 1-12");
			break;
	}
}
Output:-

Output


Spread the love

Leave a Comment


error: Content is protected !!