Examples of switch statment in c++ Programming

0

 We use the switch statement to select one of many code blocks to be executed.

Example :

switch (expression) 

{

     case x : 

      // code block

      break ;

 

     case y :

      // code block

      break ;

     default :

     // code block

All Contributions

Example of how to Write a program that appear the value of x :

#include<iostream> 
using namespace std;
int main()
{
	int x = 20;
	switch (x)
	{
	case 1: 
		cout<<"X is 10";
		 break;

	case 2: 
		cout << "X is 20"; 
		break;

	case 3: 
		cout << "X is 30"; 
		break;

	default: 
		cout<<"X is not 10, 20 or 30" ;
		break;

	}
	return 0;
}

Example of how to Write a program that make you choose a choice from 3 choices:

#include <iostream>  
using namespace std;
int main() {
	int choice;
	cout << "Enter 1, 2 or 3: ";
	cin >> choice;
	switch (choice)
	{
	case 1: 
		cout << "Choice 1"; 
		break;
	case 2: 
		cout << "Choice 2";
		break;
	case 3: 
		cout << "Choice 3"; 
		break;
	default: 
		cout << "Not 1, 2 or 3";
	}
}

How to Write a Program to build a simple calculator using switch Statement 

#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

 

How to Write a program to find weekday name based on weekday number :

#include 
using namespace std ;
Int main ()
{
	int day ;
	cout << "Enter weekday number : " ;
	cin >> day;
	switch (day) 
	{
		case 1 : 
			cout << " Monday" ;
			break ;
		case 2 :
			cout << " Tuesday" ;
			break ;
		case 3 :
			cout << "Wednesday" ;
			break ;
		case 4 :
			cout << " Thursday" ;
			break ;
		case 5 :
			cout << " Friday" ;
			break ;
		case 6 :
			cout << " Saturday" ;
			break ;
		case 7 :
			cout << " Sunday" ;
			break ;
		default :
			cout << "weekday not found" ;
	}
		return 0 ;
} 

total contributions (4)

New to examplegeek.com?

Join us