Week#8
Week#8
Week#8
Chapter 4
Making Decisions (selection)
Lecture Outline:
• Switch statement
SWITCH Statement
SYNTAX
Switch (variable)
{
case constant_1:action_1;break;
case constant_2:action_2;break;
case constant_3:action_3;break;
default:action_4;
}
The switch statement
The switch statement
SWITCH Statement
Example
char color ;
cout<<“Enter a color: “;
cin>>color;
switch (color)
{
case 'r':
case 'R': cout<<"red\n"; break;
case 'b':
case 'B': cout<<" blue\n"; break;
case 'y':
case 'Y': cout<<" yellow\n"; break;
}
SWITCH Statement
Example
char grade ;
cout<<“Enter your letter grade: “;
cin>>grade;
switch ( grade )
{
case 'a':
case 'A' : cout<<"Excellent Job”; break;
case 'b':
case 'B' : cout<<" Very Good "; break;
case 'c':
case 'C' : cout<<" Not bad "; break;
case 'f' :
case 'F' : cout<<" Fail"; break;
default : cout<<"Wrong Input ";
}
SWITCH Statement
Example
Write a program to ask the int bright ;
user for the brightness of a light cout<<“Enter the bulb brightness: “<<endl;
bulb (in Watts), and print out cin>>bright;
the expected lifetime: switch ( bright )
{
case 25 : cout<<" Lifetime is 2500 hours"; break;
Brightness Lifetime in case 40 :
hours
case 60 : cout<<" Lifetime is 1000 hours" ; break;
25 2500 case 75 :
40, 60 1000 case 100 : cout<<" Lifetime is 750 hours "; break;
default : cout<<" Wrong Input ";
75, 100 750
}
otherwise 0
//Program to implement a simple calculator using if-else statements
#include<iostream>
using namespace std;
int main()
else {
{
cout<<“wrong operation\n”;
int x,y,result, flag=0; flag=1;
char op; }
cout<<“please enter the first number: \n”; If(flag==0)
cin>>x; cout<<“result=”<<result;
cout<<“please enter the second number:\n”; return 0;
cin>>y; }
cout<<“please enter an operation(+ - * /):\n”;
cin>>op;
if (op==‘+’)
result=x+y;
else if (op==‘-’)
result=x-y;
else if (op==‘-’)
result=x-y;
else if (op==‘*’)
result=x*y;
else if (op==‘/’)
result=x/y;
//Program to implement a simple calculator using switch
#include<iostream>
using namespace std;
int main()
{
default: cout<<“wrong operation\n”;
int x,y,result, flag=0; flag=1;
char op; }
If(flag==0)
cout<<“please enter the first number: \n”; {
cin>>x; cout<<“result=”<<result;
return 0;
cout<<“please enter the second number:\n”; }
cin>>y; }