Switch Statement
Switch case statements are a substitute for long if statements that compare a variable to multiple values. After a match is found, it executes the corresponding code of that value case.
Syntax:
switch (n)
{
case 1: // code to be executed if n == 1;
break;
case 2: // code to be executed if n == 2;
break;
default: // code to be executed if n doesn't match any of the above cases
}
Key points :
1.The variable in switch should have a constant value.
2. The break statement is optional. It terminates the switch statement and moves control to the next line after switch.
3. If break statement is not added, switch will not get terminated and it will continue onto the next line after switch.
4. Every case value should be unique.
5. Default case is optional. But it is important as it is executed when no case value could be matched.
Examples:
Ques1. Write a program to write a simple calculator.
#include <iostream>
using namespace std;
int main() {
int n1,n2;
char op;
cout<<"Enter 2 numbers: ";
cin>>n1>>n2;
cout<<"Enter operand: ";
cin>>op;
switch (op)
{
case '+':
cout<<n1+n2<<endl;
break;
case '-':
cout<<n1-n2<<endl;
break;
case '*':
cout<<n1*n2<<endl;
break;
case '/':
cout<<n1/n2<<endl;
break;
case '%':
cout<<n1%n2<<endl;
break;
default:
cout<<"Operator not found!"<<endl;
break;
}
return 0;
}
Ques2. Write a program to find whether an alphabet is a vowel or a consonant.
#include <iostream>
using namespace std;
int main() {
char c;
cout<<"Enter an alphabet: ";
cin>>c;
switch (c)
{
case 'a':
cout<<"It is a vowel"<<endl;
break;
case 'e':
cout<<"It is a vowel"<<endl;
break;
case 'i':
cout<<"It is a vowel"<<endl;
break;
case 'o':
cout<<"It is a vowel"<<endl;
break;
case 'u':
cout<<"It is a vowel"<<endl;
break;
default:
cout<<"It is a consonant"<<endl;
break;
}
return 0;
}
Instagram 👇
Comments
Post a Comment