Sunday, March 12, 2017

C++ Part 19

The switch statement is the only other kind of C++ statement that implements
multi way branches.


switch Statement

switch (Controlling_Expression)
{
case Constant_1:
Statement_Sequence_1
break;
case Constant_2:
Statement_Sequence_2
break;
.
.
.
case Constant_n:
Statement_Sequence_n
break;
default:
Default_Statement_Sequence
}


Example :
#include <iostream>

using namespace std;

int main()
{
   int vehicleClass;
double toll;
cout << "Enter vehicle class '1-3': ";
cin >> vehicleClass;
switch (vehicleClass)
{
case 1:
cout << "Passenger car.";
toll = 0.50;
break;
case 2:
cout << "Bus.";
toll = 1.50;
break;
case 3:
cout << "Truck.";
toll = 2.00;
break;
default:
cout << "Unknown vehicle class!";
}
/*

If you forget this break,
then passenger cars will
pay $1.50.
You need not place a break statement in
each case. If you omit a break, that case
continues until a break (or the end of the
switch statement) is reached. */


   return 0;
}

No comments:

Digital Design Part 3

4th→ assembler translates it to the machine language. 1.6 [20] <§1.6> Consider two diļ¬€erent implementations of the same instru...