by Dinesh Thakur Category: Control Structures

The statement tests the value of a variable against a list of integer or character constants. If the variable matches any of the constants, statements associated with that constant (case) are executed. If there is more than one statement following any case, the statements are enclosed in curly brackets. Value of the switch variable should be provided before the switch statement.

 

The general syntax of switch .. case statement is :

 

switch (variable)

{

case c1:

{

statement( s);

break;

}

case c2:

{

statement(s );

break;

}

default:

{

statement( s);

}

}

 

Where c1, c2 may be integers or characters. If the value of the variable matches with c1, statements following case c1: are executed, if the value of the variable matches with c2, statements following case c2: are executed. If the value of the variable does not match with any of the given integers or characters, the statements following default: are executed. The default case option is optional and if not given, control goes outside the Switch...case statement in case a match is not found with any of the given integers or characters for the variable.

 

Write C++ Program finds the number of days in different months in a year.

 

#include <iostream.h>

#include <stdlib.h>

void main()

{

int year, days, month;

cout<<”Enter Year “;

cin>>year;

cout<<”Enter Month “;

cin>>month;

if(month<0 II month> 12 )

exit(0);

switch(month)

{

case 2 :

if((year % 400 ==0) II ((year % 4 == 0) && (year % 100 != 0)))

days = 29;

else

days = 28;

cout<<”Year “<<year<<”\n “;

cout<<”Month “<<”Days\n “;

cout<<month<<” ”<<days;

break;

case 4 :

days = 30;

cout<<”Month “<<”Days\n “;

cout<<month<<” “<<days;

break;

case 6 :

days = 30;

cout<<”Month “<<”Days\n “;

cout<<month<<” “<<days;

break;

case 9 :

days = 30;

cout<<"Month "<<"Days\n";

cout<<month<<" "<<days;

break;

case 11 :

days = 30;

cout<<"Month "<<"Days\n";

cout<<month<<" "<<days;

break;

default :

days = 31;

cout<<"Year "<<year<<"\n";

cout<<"Month "<<"Days\n";

cout<<month<<" "<<days;

}}



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles