switch:- It is a multi branch statement which can be used to
select and execute one of the available statements.
switch(value)
{
case 1: statement 1; break;
case 2: statement 2; break;
case n: statement n; break;
default: statement d;
}
Where value can be a variable of type
numeric or character. The case label 1 to n can also be written with constant
identifiers.
When the value assigned matches with case label 1 statement 1 is executed. The
break statement written after statement 1 transfers the control out of the
switch statement. When the value doesn’t match with case label 1 then it checks
with case label 2 and so on. When the value assigned doesn’t match with any of
the case labels (1 to n) then the default clause is considered and the
statement d is executed.
Default clause is optional like else clause in if-else-if-else
statement.
example:
switch(c)
{
case1: cout<< “north”; break;
case2: cout<< “south”; break;
case3: cout<< “east”; break;
case4: cout<< “west”; break;
default: break;
}
Q.
Write a program to display the grades as listed below by using switch statement
80-100 Distinction
60-79 Grade A
40-59 Grade B
Otherwise fail
#include<iostream>
void main()
{
int m;
cout<< “Enter marks scored: ”;
cin>> m;
switch( m/10 ) //marks are divided by 10
{
case 10:
case 9:
case 8: cout << “Distinction\n”; break;
case 7:
case 6: cout << “Grade A\n”; break;
case 5:
case 4: cout << “Grade B\n”; break;
default: cout << “Fail\n”; break;
}
}
Q. Write a program to design simple calculator by using switch statement
to carry out addition, multiplication, division and subtraction.
Q. Write a program to read a number from 1-7 and print day of week
corresponding to that number using switch statement.
2 takkay ki site hai janab
ReplyDeleteHello! What a adorable looking blog you have! Did you optimize this blog with our own help?
ReplyDelete