Saturday, September 7, 2013

C++ Intro To If And Switch Statements.

Posted by Unknown On 11:34 PM No comments
This tutorial introduces you to if statements and switch statements and how to use them with all kind of variables.

The switch statement

The if and if-else statements permit two way branching whereas switch statement permits multiple branching. The syntax of switch statement is:
switch (var / expression) 

   case constant1 : statement 1; 
   break; 
   case constant2 : statement2; 
   break; 
   .
   .
   default: statement3; 
   break; 
}

The execution of switch statement begins with the evaluation of expression. If the value of expression matches with the constant then the statements following this statement execute sequentially till it executes break. The break statement transfers control to the end of the switch statement. If the value of expression does not match with any constant, the statement with default is executed.
Some important points about switch statement
  • The expression of switch statement must be of type integer or character type.
  • The default case need not to be used at last case. It can be placed at any place.
  • The case values need not to be in specific order.
The switch statement is almost the same as an “if statement”. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variables equals the condition, the instructions are executed. It is also possible to add a default. If none of the variables equals the condition the default will be executed. See the example below:
::--In simple words it is used it cheak many conditions
a simple switch (aprogram to find the numbered entered)


















 output:-- so it you enter number 3 the process goes to case 3 and the output goes as
cout<<" you've entered number 3"<<endl;
for  example::-- let us see  how to find a day of the week
the program in code
#include<iostream>
using namespace std;
int main()
{i
nt day;
cout<<" enter the day of te week(1-7)\n";
cin>>day;switch(day)
{
case 1:cout<<"\nsunday";break;
case 2:cout<<"\nmonday";break;
case 3:cout<<"\ntuesday";break;
case 4:cout<<"\nwednesday";break;
case 5:cout<<"\n thursday";break;
case 6:cout<<"\n friday";break;
case 7:cout<<"\n saturday";break;
default:cout<<"wrong entry";break;
}
return 0;
}
pic





















A PROGRAM TO CONVERT FAHRENHEIT TO CELSIUS AS A MENU DRIVEN PROGRAM I SWITCH STATEMENT


0 comments:

Post a Comment