Advertisements
Advertisements
प्रश्न
Explain switch case statement with example.
उत्तर
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 conditional statement is used to transfer control from current statement to another statement?
_______ statement can be used as alterative to if-else statement.
Which statement in switch case is used to exit the statement once the appropriate choice is found?
What will be the output for the following snippet:
For (var n=0; n<10; n++)
{
if (n==3)
{
break;
}
document write (n+”<br>”);
}
List out the various branching statements in JavaScript?
Write the syntax for else-if statement.
What message will be displayed, if the input for age is given as 20, for the following snippet?
Rewrite the following code using the if-else statement:
int m = 400;
double cl). = (m>300) ? (m/10.0) * 2; (m/20.0) - 2;
Give the output of the following program segment:
int n = 4279; int d;
while(n>0)
(d=n%10;
System.out.println(d);
n=n/100;
}
Which of the following is not true with regards to a switch statement?