Sunday, July 20, 2014

Using switch...case statement in C++

Conditional Processing Using switch...case
The objective of switch-caseis to enable you to check a particular expression against a host of possible constants and possibly perform a different action for each of those different values. The new C++ keywords you would often find in such a construct are switch, case, default, and break.
Syntax:
switch(expression){
case constant1:
          Statements for first case;
          break;
case constant2:
          Statements for second case;
          break;
// And so on…
default:
          DoStuffWhenExpressionIsNotHandledAbove;
          break;
}

Example:
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
int month, year;
cout<<"Input month"; cin>>month;
cout<<"Input year"; cin>>year;
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
cout<<"Month is 31 days"; 
                        break;
case 4: case 6: case 9: case11:
cout<<"Month is 30 days";  
                        break;
case 2:
if((year%4==0 && year%100!=0)|| year%400==0)
cout<<"Month is 29 days"; 
else
cout<<"Month is 28 days"; 
}
getch();
return 0;

}


No comments:

Post a Comment