switch statement

Switch statement:

The problem in if-statement is the complexity to read and follow. Even it may be confuse the programmer who designed it. The switch statement tests the value of the variable with a list of case values and when a match is found, and then the block of that particular case will be executed.

Syntax:

switch(expression)

{

case: 1

block-1

break;

case: 2

block-2

break;

default:

default-block

break;

}

As is the above syntax we will give the expression in the form of variable. And according to that given value it will executes the case. If any of the case is not matched then the default case will be executed. And we have used the break statement which will help to exit from the switch statement. The break will skip the rest of the cases for comparisons, and this saves execution time.

Program:

PROGRAM TO DISPLAY MONDAY TO SUNDAY USING SWITCH CASE

#include<stdio.h>

#include<conio.h>

void main()

{

int n;

clrscr();

printf(“Enter any number b/w 1 and 7: “);

scanf(“%d”,&n);

switch(n)

{

case 1:

printf(“Sunday is the first day of the week”);

break;

case 2:

printf(“Monday is the second day of the week”);

break;

case 3:

printf(“Tuesday is the third day of the week”);

break;

case 4:

printf(“Wednesday is the fourth day of the week”);

break;

case 5:

printf(“Thursday is the fifthe day of the week”);

break;

case 6:

printf(“Friday is the sixth day of the week”);

break;

case 7:

printf(“Saturday is the seventh day of the week”);

break;

default:

printf(“You have entered a wrong choice”);

}

getch();

}

Posted in C

Leave a Reply

Your email address will not be published. Required fields are marked *