The switch statement is c++ multi-way branch statement. It is used to take the place of long if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined. The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For example, consider the following program:
Syntax:
switch ( expression )
{
case 1 :
case 2 :
case 3 :
case 4 :
// code inside the combined case
break;
case 5 :
case 6 :
// code inside the combined case value
break;
.
.
default :
// code inside the default case .
}
This program takes an input of a month number from the user (between 1 and 12) and then uses a switch statement to determine the number of days in that month. The switch statement has cases for each month with 31 days (January, March, May, July, August, October, and December). For these months, the program outputs "Days : 31".
The switch statement also has a case for February, which can have either 28 or 29 days depending on whether or not it's a leap year. If the user enters 2 for the month, the program outputs "Days : 28 | 29".
The switch statement has cases for the remaining months with 30 days (April, June, September, and November). For these months, the program outputs "Days : 30". If the user enters a value for the month that is not between 1 and 12, the default case of the switch statement is executed and the program outputs "Invalid Month Value". At the end of the program, it returns 0 to indicate successful execution.
#include<iostream> using namespace std; int main() { int m; cout<<"\nEnter The Month in Number (1-12)"; cin>>m; switch(m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout<<"Days : 31"<<endl; break; case 2: cout<<"Days : 28 | 29"<<endl; break; case 4: case 6: case 9: case 11: cout<<"Days : 30"<<endl; break; default: cout<<"Invalid Month Value"<<endl; break; } return 0; }
Enter The Month in Number (1-12)6 Days : 30To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions