Advertisements
Advertisements
प्रश्न
Explain switch case statement with example.
Advertisements
उत्तर
JavaScripts offers the switch statement as an alternate to using if…else structure. The switch statement is especially useful when testing all the possible results of an expression.
The syntax of a switch structure as the following:
switch(expression)
{
` case label1:
statements1;
break;
case label2:
statements2;
break;
case labeln;
statements - N;
break;
default:
statements;
}
Working of switch statement:
The switch statement begins by evaluating an expression placed between parenthesis, much like the if statement. The result compared to labels associated with case structure that follow the switch statement. If the result is equal to a label, the statements in the corresponding case structure are executed.
The default structure is can be at the end of a switch structure if the result of the expression that do not match any of the case labels. The break statement is also used commonly within switch to exit the statement once the appropriate choice is found.
Example:
HTML CODE
<Html>
<Head>
<Title>Program - To test witch command in JavaScript </Title>
</Head>
<Body>
<script language="javascript" type="text/javascript">
var grade=0;
var marks=prompt(“Please enter your marks/100:”,”0”);
if(marks>90)
{grade=1;}
else if(marks>70)&&(marks<=90)
{grade=2;}
else if(marks>50)&&(marks<=70)
{grade=3;}
else if(marks>40v)&&(marks<=50)
{grade=4;}
else
{grade=5;}
switch(grade)
{
case 1:
document.write("Your Grade is Outstanding..");
break;
case 2:
document.write("Your Grade is Excellent..");
break;
case 3:
document.write("Your Grade is Good..");
break;
case 4:
document.write("Your Grade is Satisfectory..");
break;
default:
document.write("Your Grade Poor and have to re-appear Exam..");
}
</script>
</Body>
</Html>
The output will be



APPEARS IN
संबंधित प्रश्न
Which statement in switch case is used to exit the statement once the appropriate choice is found?
In which loop the condition is evaluated, before executing a statement?
The _______ statement is especially useful when testing all the possible results of an expression.
What is meant by conditional statements in JavaScript?
Differentiate the break and continue statement.
What is if statement and write its types.
What message will be displayed, if the input for age is given as 20, for the following snippet?
Consider the following program segment and select the output of the same when n = 10:
switch(n)
{Case 10: System.out.println(0*2);
case 4: System.out.println(n*4); break;
default : Syslem.out.println(n);
}Which of the following is not true with regards to a switch statement?
Rewrite the following code using single if statement.
if(code=='g')
System.out.println("GREEN");
else if(code=='G')
System.out.println("GREEN");