Saturday, 1 March 2014

Switch Statement Example - Number to Day Converter

Let me first clear up the aim. User enters a number from 1 to 7 and we output corresponding day, where 1 is Sunday and 7 is Saturday. We here use 'switch' statement, the syntax of which is given:
switch(expression){
                 case constant - 0:
                           statement(s);
                           break;
                 case constant - 1:
                           statement(s);
                           break;
                               .
                               .
                               .
                 case constant - (n-1):
                           statement(s);
                           break;
                 default:
                           statement(s);
       }

Code:

#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int ch;
    cout<<"Enter the number of the day\n";
    cin>>ch;
    switch(ch)
    {
              case 1:
                   cout<<"Sunday";
                   break;
              case 2:
                   cout<<"Monday";
                   break;
              case 3:
                   cout<<"Tuesday";
                   break;
              case 4:
                   cout<<"Wednesday";
                   break;
              case 5:
                   cout<<"Thursday";
                   break;
              case 6:
                   cout<<"Friday";
                   break;
              case 7:
                   cout<<"Saturday";
                   break;
    }
    getch();
}
Working:
           We just input the number from the user, and output corresponding days using switch statement. Switch statement is just like an if-else statement.

Sample output of the above program is:



Happy Coding!
:)

No comments:

Post a Comment

You might also like