Switch Statement in C++: Prepared By: Zeeshan Mubeen

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 7

Switch Statement in C++

Prepared By:
Zeeshan Mubeen
Switch Statement in C++

• A switch statement allows a variable to be


tested for equality against a list of values.
• Each value is called a case, and the variable
being switched on is checked for each case.
• A switch statement is a type of selection
control mechanism used to allow the value of
a variable or expression to change the
control flow of program execution via search
and map.
Switch Statement Syntax
switch (selector)
{ case V1:
statements1;
break;
case V2:
statements2;
break;

default:
statements_n;
}
Example 4: C++ Program

// File: music.cpp
/*The program corresponds to Example 5 on slide 31. It reads a letter and displays a suitable
musical note (do, re, mi, etc.)*/
#include <iostream.h>
void main ( )
{ char ch ;
cin >> ch ;
switch ( ch )
{ case ‘c’ : cout << “ do “ << endl; break;
case ‘d’ : cout << “ re “ << endl; break;
case ‘e’ : cout << “ mi “ << endl; break;
case ‘f’ : cout << “ f “ << endl; break;
case ‘g’ : cout << “ sol “ << endl; break;
case ‘a’ : cout << “ la “ << endl; break;
case ‘b’ : cout << “ ti “ << endl; break;
default : cout << “ Invalid note was read “ << endl;
}
Example 6: C++ Program
// File: circle.cpp
/*This program corresponds to Example 6 on slide 33. It is a menu driven program. It
calculates the area of the circle if letter a is read or calculates the circumference if letter
c is read.*/
#include <iostream.h>
void main ( )
{ char ch ; float radius, area, circum;
cout << “ Enter the radius of a circle: “ ;
cin >> radius;
cout << “ Enter a to calculate the area of a circle or c to calculate its circumference:”
cin >> ch ;
switch (ch)
{ case ‘a’ : area = 3.14* radius * radius;
cout << “ Area = “ << area << endl; break;
case‘c’ : circum = 2 * radius * 3.14f ;
cout << “ Circumference = “ << circum << endl; break;
default : cout << “ Invalid letter was read “ << endl;
}
}
#include <iostream.h>
void main ( )
{ char ch ;
cout << “ \n Enter the grade of student: “<<endl ;
cin >> ch;
switch (ch)
{
case ‘A’ :
case ‘a’ :
cout<<”Excellent”;
break;
case ‘B’ :
case ‘b’ :
cout<<”Good”;
break;
case ‘C’ :
case ‘c’ :
cout<<”O.K”;
break;
case ‘D’ :
case ‘d’ :
case ‘F’ :
case ‘f’ :
cout<<”poor”;
break;
default: cout<<”invalid letter grade”;
}
}
#include <iostream.h>
void main()
{ int x,y;
cout << "Enter 2 integer number: ";
cin >> x>>y;
switch (x+y)
{ case 7: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!\n";
break;
case 4: cout << "Nice Pick!\n";
case 3: cout << "Excellent!\n";
break;
case 2: cout << "Masterful!\n";
break;
case 1: cout << "Incredible!\n";
break;
default: cout << "Too large!\n";
}
cout << "\n\n";
}

You might also like