Switch case practice in C++ | part 1

Here is Video of Switch case Practice Programs in C++

Task 1

Write a program that ask the user to enter two numbers and the operator. If the user enter + then sum two numbers and print result. If user enter – then subtract and print result. User can enter +,-,*,/,%

Code

#include<iostream>
using namespace std;
int main()
{
	//two numbers required
	float n1,n2;
	//input operator save it in character
	char op;
	cout<<"Enter Two Numbers : \n";
	cin>>n1>>n2;
	cout<<"Enter Operator (+,-,*,/,%) : ";
	cin>>op;
	switch(op)
	{
		case '+':
			cout<<endl<<n1<<" + "<<n2<<" = "<<n1+n2;
			break;
		case '-':
			cout<<endl<<n1<<" - "<<n2<<" = "<<n1-n2;
			break;
		case '*':
			cout<<endl<<n1<<" * "<<n2<<" = "<<n1*n2;
			break;
		case '/':
			cout<<endl<<n1<<" / "<<n2<<" = "<<n1/n2;
			break;
		case '%'://it can't be applied on float type so type casting
			cout<<endl<<int(n1)<<" % "<<int(n2)<<" = "<<int(n1)%int(n2);
			break;
		default:
			cout<<"\nInvalid Operator :( ";
	}
}

Output

Enter Two Numbers :
86
45
Enter Operator (+,-,*,/,%) : +

86 + 45 = 131

Task 2

Write a program that ask the user to choose the vehicle for the parking and number of days and then display the total charges..
Menu
C — Car 1 day charge = 30 Rs
M — Motorcycle 1 Day charge = 20Rs
B –Bus 1 day charge = 40Rs

Code

#include<iostream>
using namespace std;
int main()
{
	//variables required 2
	char v;//type of vehicle
	int days;//number of days
	cout<<"Choose the Vehicle for which You Need Parking Space : ";
	cout<<"\nC --> Car                  1 day charge = 30 Rs";
	cout<<"\nM --> Motorcycle           1 Day charge = 20Rs ";
	cout<<"\nB --> Bus		    1 day charge = 40Rs\n";
	cin>>v;
	cout<<"Number of Days : ";
	cin>>days;
	switch(v)
	{
		case 'C':
			cout<<"Your Total Bill for "<<days<<" Days is : "<<days*30;
			break;
		case 'M':
			cout<<"Your Total Bill for "<<days<<" Days is : "<<days*20;
			break;
		case 'B':
			cout<<"Your Total Bill for "<<days<<" Days is : "<<days*40;
			break;
		default:
			cout<<"Invalid Input : ";
	}
}

Output

Choose the Vehicle for which You Need Parking Space :
C --> Car                  1 day charge = 30 Rs
M --> Motorcycle           1 Day charge = 20Rs
B --> Bus                  1 day charge = 40Rs
M
Number of Days : 6
Your Total Bill for 6 Days is : 120

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *