Lab 5.2
Lab 5.2
Lan
Lab 5.2
Switch Case
The switch statement allows us to execute one code block among many alternatives.
It is similar to if...else..if, however, the syntax of the switch statement is
much easier to read and write.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to x, statements after
case x are executed until break is encountered. If there is no match, the default
statements are executed.
1
C++ Lab Module
Lan
2
C++ Lab Module
Lan
Example 1:
int day = 4;
switch (day)
{
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << “The day does not EXIST!!”;
}
Output:
Thursday
3
C++ Lab Module
Lan
Example 2:
int main()
{
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
cout << "Error! The operator is not correct";
break;
}
}
Output:
Enter an operator (+, -, *, /): +
Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8
4
C++ Lab Module
Lan
Exercise:
1. Write a program with Switch Case statement to determine which college a student is
placed based on his/her college code. If the code is between 1 and 4, the student is
Non-Resident.
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if (number == 1 )
{
cout << "You are eligible for a 10% discount << endl;
}
else if (number == 2)
{
cout << "You are eligible for a 50% discount << endl;
}
else
{
cout << "No Discount.";
}
}