Tutorial dan Contoh switch Statement C++

Artikel Terkait Tutorial C
Consider a situation in which, only one block of code needs to be executed among many blocks. This type of situation can be handled using nested if...else statement but, the better way of handling this type of problem is using switch...case statement.

Syntax of switch

switch (n) {
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant in case, the relevant codes are executed and control moves out of the switch statement. If the n doesn't matches any of the constant in case, then the default statement is executed and control moves out of switch statement.

Flowchart of switch Statement

C++ Flow Control, C++ if else, C++ for Loop, C++ do while Loop, C++ break & continue, C++ switch Statement, C++ goto Statement

Example 1: C++ switch Statement

/* C++ program to demonstrate working of switch Statement */
/* C++ program to built simple calculator using switch Statement */
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout
<<"Select an operator either + or - or * or / \n";
cin
>>o;
cout
<<"Enter two operands: ";
cin
>>num1>>num2;

switch(o) {
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:

/* If operator is other than +, -, * or /, error message is shown */
printf
("Error! operator is not correct");
break;
}

return 0;
}

Output

Select an operator either + or - or * or /
-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2
The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed.

Tag : C++ Flow Control, C++ if else, C++ for Loop, C++ do while Loop, C++ break & continue, C++ switch Statement, C++ goto Statement


Selain Sebagai Penyedia Panduan Belajar Database dan Tutorial Pemrograman, Kami Juga Membagikan Kumpulan Source Code Program Aplikasi dan Ebook Pemrograman Terlengkap yang Bisa Anda Dapatkan Secara Gratis di Halaman :


Rekomendasi Web Hosting
  1. 20rb perbulan. Diskon hingga 40% kode kupon: MCP Daftar disini (apache).
  2. 10rb perbulan. Diskon hingga 75% kode kupon: MCP Daftar disini (litespeed).
  3. 10rb perbulan. Diskon hingga 70% kode kupon: aff-MCP Daftar disini (apache).