Switch Statement in C++

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Swtich Case in cpp
/*
  switch(value)
  {
   case one: statement1 
   case two:statement2
   case
   default: 
  }
*/
#include<iostream>
using namespace std;
int getValue();
int main()
{
    system("cls");
    int n;
    cout<<"Enter a number";
    cin>>n;
    switch(n)  //n=2
    {
        case 1: cout<<"One";break;
        case 2: cout<<"Two"; break;  
        case 3: cout<<"Three";break;
        case 4: cout<<"Four";break;
        case 5: cout<<"Five";break;
        default:cout<<"Invalid Number";break;
    }
    cout<<"\n Bye Bye";
    return 0;
}

Program 2

// Vowel 
#include<iostream>
using namespace std;
int getValue();
int main()
{
     char ch;
     system("cls");
     cout<<"Enter a character";
     cin>>ch;   
     switch(ch)
     {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':cout<<"Vowel";break;

        default:cout<<"Not a Vowel";
     }
     return 0;
}

Program 3

#include<iostream>
using namespace std;
int getValue();
int main()
{
    system("cls");
     switch(int n=getValue())
     {
        case 1:cout<<"One";break;
        case 2:cout<<"Two";break;
        case 3:cout<<"Three";break;
        case 4:cout<<"Four";break;
     }
}
int getValue()
{
    int x;
    cout<<"Enter a number";
    cin>>x;
    return x;
}

Program 4

// Simple Calculator Project
#include<iostream>
using namespace std;
int main()
{
    int n1,n2;
    char opr;
    system("cls");
    cout<<"-----------Simple Calculator---------------\n\n";
    cout<<"\n First Number: ";
    cin>>n1;
    cout<<"+ , - , * , / ,% :  ";
    cin>>opr;
    cout<<"\nSecond Number: ";
    cin>>n2;
    switch(opr)
    {
        case '+': cout<< n1+n2;break;
        case '-': cout<< n1-n2;break;
        case '*': cout<< n1*n2;break;
        case '/': 
         {
               if(n2!=0)
                cout<<n1/n2;
               else
               cout<<"Can't divide by zero";
               break;
         } 
       case '%': 
         {
               if(n2!=0)
                cout<<n1%n2;
               else
               cout<<"Can't divide by zero";
               break;
         }   
        default: cout<<"Invalid operator "; 
    }
    
    return 0;
}

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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