Tutorial dan Contoh switch Statement Pemrograman C++

Pada kesempatan ini Mycoding.net berbagi artikel tentang yang berjudul .

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 :

Kategori artikel yang terkait dengan C Plus Plus

C Plus Plus, Panduan C++, Belajar C++ Lengkap, Tutorial C++, Belajar C++ Pdf, Pemrograman C++
Untuk mendapat notifikasi artikel terbaru, masukkan e-mail anda disini :
Selanjutnya cek e-mail untuk verifikasi.
Kincai Coding Panduan Belajar Database dan Tutorial Pemrograman Terlengkap di Indonesia. Dapatkan Kumpulan Source Code Program Aplikasi dan Ebook Secara Gratis. Ikuti kami di Facebook, Instagram & Sosial Media Lainnya.