The Switch Case Statement In Visual C# .Net

The switch case statement is also used for making decision, unlike the if else statement , we can not test conditions like "greater than" or "less than" . in switch case we can test the value of a variable and decide what to do if a particular value is stored in the variable.

the syntax for switch statement below


switch(varable to test)

{

case value 1 :
statements if value 1 stored in the variable;
break;

case value 2 :
statements if value 2 stored in the variable;
break;

*
*
default:
statements if none of the values match;
break;
}

example

the user will enter a weekday number( 1 to 7 ) and the program will display the name of the corresponding day




static void main(string[]args)

{

int day;
console.writeline("enter a weekday number (1-7)");
day = int.parse(console.readline());switch(day)

{

case 1 :console.writeline("monday");

break;

case 2 :console.writeline("tuesday");

break;

case 3 :console.writeline("wednesday");

break;

case 4 :console.writeline("thursday");

break;

case 5 :console.writeline("friday");

break;

case 6 :console.writeline("saturday");

break;

case 7 :console.writeline("sunday");

break;

default: console.writeline("input invalid");

break;

}

}


in the codes up , the value stored in the variable "day" is tested . if the value is 1 the first case will match and the statements in it will execute then the keyword "break" will terminate the switch case if the value is 2 the second case will match and if the user enteres a value that does not match any case statement in the default section will execute.

1 comments:

Post a Comment

Note: Only a member of this blog may post a comment.