DEV Community

Munisa Kuranbekova
Munisa Kuranbekova

Posted on

Switch statement haqida

Assalomu aleykum! Bugungi postimiz switch statement haqida bo'ladi.
Switch - ifga o'xshash bo'lgan gramatika bo'lib , ifdan soddaroq tuzilgan. Ularning asosiy farqlaridan biri shuki , if orqali hamma datatiplarni ishlatish mumkin bo'lsa, switch statementda faqat int va chardn foydalanish mumkin.
Switch expression
{
case Constant 1:
statement 1
break;
case Constant 2:
statement 2
break;
case Constant 3:
statement 3
break;
}

Yuqorida yozilgan strukturamiz switchning syntaxi hisoblanadi.Kodga o'tadigan bo'lsak:

#include <iostream>

using namespace std;

int main()
{  

    int son;
    cin>> son;

switch(son)
{
case 1:
cout << " One " << endl;

case 2:
cout << " Two " << endl;

case 3:
cout << " Three " << endl;

case 4:
cout << " Four " << endl;

 default:
cout << "none" << endl;   

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Ushbu kodni run qiladigan bo'lsak consolega kodimizga to'g'ri kelgan sonlarni chop etadi. To'g'ri javobning bir o'zi kerak bo'lsa , har bitta cout komandasining tagidan break; deb yozib chiqishimiz zarur.

Top comments (0)