You are on page 1of 5

Page 1 of 5

TASK #1:
Write a program using switch statement to find larger number among two variables.
Variables should be user defined.
SOLUTION:
#include<iostream>
using namespace std;
int main()
{
int n, m;
cout<<"Enter value 1: "; cin>>n;
cout<<"Enter value 2: "; cin>>m;
switch(n>m)
{
case 0: cout<<"\nValue "<<m<<" is greater."; break;
case 1: cout<<"\nValue "<<n<<" is greater."; break;
default: cout<<"\nInvalid Operation";
}
}

Task #2:
Write a program using switch statement to find the number is even or odd. The number
should be user defined.
SOLUTION:
#include<iostream>
using namespace std;
Page 2 of 5

int main()
{
int n;
cout<<"Enter any number : "; cin>>n;
switch(n%2==0)
{
case 0: cout<<n<<" is an Odd number."; break;
case 1: cout<<n<<" is an Even number."; break;
default: cout<<"\nInvalid Operation";
}
}

TASK #3:
Write a program using switch statement to find the grade of students.
The detail is as follow.
grade >= 90 → Grade A
grade >= 80 → Grade B
grade >=70 → Grade C
grade >=60 → Grade D
SOLUTION:
#include <iostream>
using namespace std;
int main()
{
int marks;
cout<<"Enter marks of student: "; cin>>marks;
switch(marks/10)
{
case 10:
Page 3 of 5

case 9: cout<<"Grade is: A"; break;


case 8: cout<<"Grade is: B"; break;
case 7: cout<<"Grade is: C"; break;
case 6: cout<<"Grade is: D"; break;
case 4: case 3: case 2: case 1: case 0:
cout<<"You are Fail."; break;
default: cout<<"Sorry! try again";
}
}

TASK #4:
Write a program using switch statement to create a calculator.
SOLUTION:
#include<iostream>
using namespace std;
int main()
{
int n, m;
char op='K';
do
{
cout<<"Enter Value1, Operator, Value2: "; cin>>n>>op>>m;
switch(op)
{
case '+': cout<<"Sum is: "<<(n+m); break;
case '-': cout<<"Difference is: "<<(n-m); break;
case '*': cout<<"Product is: "<<(n*m); break;
Page 4 of 5

case '/': cout<<"Division is: "<<(n/m); break;


default: cout<<"\nInvalid Operation";
}
cout<<"\nDo you want to perform another operation (y/n)? : ";
cin>>op;
}
while(op=='y');
}

TASK #5:
Write a program using switch statement to find the condition of water whether it is Ice,
Water or Steam. Display the menu also as under.
HINT: Temperature Less than 0 = ICE
Temperature Greater than 0 & Less than 100 = Water
Temperature Greater than 100 = STEAM
SOLUTION:
#include<iostream>
using namespace std;
int main()
{
float val;;
cout<<"Enter value: "; cin>>val;
switch((-1*(val<0)) + (1*(val>0 && val<100)) + (2*(val>100)) + (3*(val==0
|| val==100)))
Page 5 of 5

{
case -1: cout<<"\nWater is in the form of = ICE"; break;
case 1: cout<<"\nWater is in the form of = WATER"; break;
case 2: cout<<"\nWater is in the form of = STEAM"; break;
case 3: cout<<"\nCondition is not defined in question"; break;
default: cout<<"\nInvalid Operation";
}
}

Prepared By: Khawar Khalil

You might also like