MATLABMATLAB · Chapterبەش 5 · Lectureوانە 5.3

The switch Statementڕستەی switch

Choose one of many paths by a single value with switch, case and otherwise: only the first match runs (no fall-through), text cases match exactly, a cell array gives several values one case, and fix(mark/10) turns ranges into values — with the lab's day-name, grade and salary programs tested and corrected (100 → F becomes case {9, 10}).

بە switch، case و otherwise بە یەک یەکێک لە چەندین ڕێگا هەڵبژێرە: تەنها یەکەم یەکسانبوون جێبەجێ دەبێت (بێ )، caseـی دەقی تەواو یەکسان دەبن، ⁦cell array⁩ چەند دەخاتە یەک caseـەوە و ⁦fix(mark/10)⁩ هەر دەکات بە یەک — لەگەڵ ناوی ڕۆژ، پلە و مووچەی تاقیگە، تاقیکراوە و چاککراو (نمرەی ⁦100⁩ کە F وەردەگرت، بە case {⁦9, 10⁩} چاک دەکرێت).

14 min read14 خولەک خوێندنەوە · 13 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Write a switch with case and otherwise and explain why only the first matching case runs.
  • Switch on numbers and on text, using lower for capitals and braces for several values.
  • Turn ranges into values with fix and test the boundaries, including the mark 100.
  • Decide between switch and if, and avoid comparisons inside a case.
  • switchـێک بە case و otherwise بنووسیت و ڕوونی بکەیتەوە بۆچی تەنها یەکەم caseـی یەکسان جێبەجێ دەبێت.
  • لەسەر ژمارە و لەسەر دەق switch بکەیت، بە lower بۆ پیتی گەورە و کەوانەی لووتکەدار بۆ چەند .
  • بە fix هەر بکەیت بە یەک و سنوورەکان تاقی بکەیتەوە، لەوانە نمرەی ⁦100⁩.
  • لە نێوان switch و ifـدا بڕیار بدەیت و خۆت لە بەراورد لەناو caseـدا بپارێزیت.

One value, many pathsیەک نرخ، چەندین ڕێگا

Often a program must choose one of many actions by the value of a single variable: a menu choice, a day number, a grade group. You could write a long if … elseif … elseif … chain, but the says it more clearly. MATLAB compares the value after switch with each case in turn; otherwise catches every value no case matched:

زۆرجار دەبێت بە تەنها یەک یەکێک لە چەندین کار هەڵبژێرێت: هەڵبژاردنێکی ، ژمارەی ڕۆژێک، کۆمەڵەیەکی نمرە. دەتوانیت زنجیرەیەکی درێژی if … elseif … elseif … بنووسیت، بەڵام ڕوونتر دەیڵێت. MATLAB ئەو دوای switch یەک لە دوای یەک لەگەڵ هەر caseـێک بەراورد دەکات؛ otherwise هەموو ئەو دەگرێت کە هیچ case یەکسانیان نەبوو:

The shape of a switchشێوەی switchMATLABType in a terminalلە تێرمیناڵدا بینووسە
switch expression
    case value1
        % statements for value1
    case value2
        % statements for value2
    otherwise
        % statements when nothing matched
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The expression must give one number or one piece of text (MathWorks: a scalar or a character vector).

دەبێت یەک ژمارە یان یەک پارچە دەق بدات (MathWorks: یان ⁦character vector⁩).

Lineدێڕی 6

otherwise is optional; without it, an unmatched value simply does nothing.

otherwise ئارەزوومەندانەیە؛ بەبێ ئەو، کە یەکسانی نەبێت هیچ ناکات.

A switch drawn as a railway junction. The value op = 'mul' leaves on the main track and meets a vertical line of five branches: case 'add' → a + b, case 'sub' → a − b, case 'mul' → a * b, case 'div' → a / b, and otherwise → disp('Unknown') at the bottom. Only the case 'mul' branch is highlighted. Notes: MATLAB checks the cases from the top; the first match runs, then the switch ends; otherwise is used when no case matched — the last siding.switch وەک یەکتربڕی هێڵی شەمەندەفەر کێشراوە. نرخەکە op = 'mul' لە هێڵی سەرەکییەوە دەڕوات و دەگاتە هێڵێکی ستوونی بە پێنج لقەوە: case 'add' → a + b، case 'sub' → a − b، case 'mul' → a * b، case 'div' → a / b و لە خوارەوە otherwise → disp('Unknown'). تەنها لقی case 'mul' ڕەنگ کراوە. تێبینی: MATLAB بەشەکانی case لە سەرەوە دەپشکنێت؛ یەکەم یەکسانبوون جێبەجێ دەبێت، پاشان switch کۆتایی دێت؛ otherwise کاتێک بەکار دێت کە هیچ case یەکسان نەبوو — دوایین ڕێگای لاوەکی.
A switch is like a railway junction: the value takes the first matching trackswitch وەک یەکتربڕی هێڵی شەمەندەفەرە: یەکەم هێڵی یەکسان دەگرێتCêIT
Quick checkپشکنینی خێراWhat happens when the switch value matches no case and there is no otherwise?چی ڕوودەدات کاتێک switch لەگەڵ هیچ case یەکسان نەبێت و otherwise نەبێت؟

One value, many pathsیەک نرخ، چەندین ڕێگا

Only the first match runsتەنها یەکەم یەکسانبوون جێبەجێ دەبێت

When a case matches, MATLAB runs its statements and leaves the switch. MathWorks puts it plainly: the MATLAB switch does not fall through like a switch in C. In C, Java or JavaScript, a matching case keeps running into the cases below it unless you write break — that is a famous source of bugs. MATLAB needs no break, and if two cases could match the same value, only the first one ever runs.

کاتێک case یەکسان دەبێت، MATLAB جێبەجێ دەکات و switch جێدەهێڵێت. MathWorks بە ڕوونی دەیڵێت: switchـی MATLAB وەک switch لە C ناکات. لە C، Java یان JavaScriptـدا، caseـێکی یەکسان بەردەوام دەبێت بۆ ناو caseـەکانی خوارەوەی، مەگەر break بنووسیت — ئەو سەرچاوەیەکی ناسراوی . MATLAB پێویستی بە break نییە و ئەگەر دوو case بتوانن یەکسان بن لەگەڵ هەمان ، تەنها یەکەمیان جێبەجێ دەبێت.

Two cases could match; only the first runsدوو case دەتوانن یەکسان بن؛ تەنها یەکەمیان جێبەجێ دەبێتMATLABType in a terminalلە تێرمیناڵدا بینووسە
n = 2;
switch n
    case 2
        disp('two')
    case {1, 2, 3}
        disp('small')
    otherwise
        disp('other')
end
The taxi garage in the bazaarگەراجی تاکسی لە بازاڕ

At a taxi garage the dispatcher shouts the destination and each line of cars waits for one city: Erbil, Duhok, Kirkuk. A passenger walks to the first line whose sign matches and gets in; nobody tries the other lines after that. A passenger for a city with no line goes to the general taxis — that is otherwise.

لە گەراجی تاکسیدا بانگکەرەکە شوێنی مەبەست هاوار دەکات و هەر ڕیزێک ئۆتۆمبێل چاوەڕێی یەک شار دەکات: هەولێر، دهۆک، کەرکووک. سەرنشینێک دەچێت بۆ یەکەم ڕیز کە تابلۆکەی یەکسانە و سوار دەبێت؛ دوای ئەوە کەس ڕیزەکانی تر تاقی ناکاتەوە. سەرنشینێک بۆ شارێک کە ڕیزی نییە دەچێت بۆ تاکسییە گشتییەکان — ئەوە otherwiseـە.

Where the analogy stops workingسنووری ئەم نموونەیە

A switch only compares for equality. A passenger who says “any city more than 100 km away” cannot be matched by a case; that needs an if.

switch تەنها یەکسانبوون بەراورد دەکات. سەرنشینێک کە دەڵێت «هەر شارێک لە ⁦100⁩ کیلۆمەتر دوورتر» بە case یەکسان ناکرێت؛ ئەوە پێویستی بە ifـە.

Quick checkپشکنینی خێراIn the code above, what is printed for n = 3?لە کۆدی سەرەوەدا، بۆ n = 3 چی چاپ دەکرێت؟

A number in, a day name outژمارەیەک دێتە ژوورەوە، ناوی ڕۆژێک دەچێتە دەرەوە

A lab question asks for the name of the day from its number, counting Sunday as day 1 (MATLAB's own weekday function counts the same way). Each number is one case; any other number goes to otherwise:

پرسیارێکی تاقیگە ناوی ڕۆژ لە ژمارەکەیەوە دەخوازێت، بە ژماردنی یەکشەممە وەک ڕۆژی 1 ( weekdayـی MATLAB خۆیشی بەم شێوەیە دەژمێرێت). هەر ژمارەیەک یەک caseـە؛ هەر ژمارەیەکی تر دەچێت بۆ otherwise:

Day names (a sample run)ناوی ڕۆژەکان (جارێک جێبەجێکردن)day_name.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
day = input('Day number (1-7): ');
switch day
    case 1
        disp('Sunday')
    case 2
        disp('Monday')
    case 3
        disp('Tuesday')
    case 4
        disp('Wednesday')
    case 5
        disp('Thursday')
    case 6
        disp('Friday')
    case 7
        disp('Saturday')
    otherwise
        disp('Unknown day number')
end
The seven cases and the otherwiseحەوت caseـەکە و otherwise
NumberژمارەPrintedچاپ دەکرێتIn Kurdishبە کوردی
1SundaySundayیەکشەممە
2MondayMondayدووشەممە
3TuesdayTuesdayسێشەممە
4WednesdayWednesdayچوارشەممە
5ThursdayThursdayپێنجشەممە
6FridayFridayهەینی
7SaturdaySaturdayشەممە
9Unknown day number—
Quick checkپشکنینی خێراWhat does the program print for the input 0? بۆ 0 چی چاپ دەکات؟

Switching on text: a small calculatorswitch لەسەر دەق: حاسیبەیەکی بچووک

A switch also works with text. For text, MATLAB compares like strcmp, so the match must be exact — and it is : 'Add' does not match case 'add'. Pass the text through lower first and the user may type Add, ADD or add. Here is a four-operation calculator with a text :

switch لەگەڵ دەقیش کار دەکات. بۆ دەق، MATLAB وەک strcmp بەراورد دەکات، بۆیە یەکسانبوون دەبێت تەواو بێت — هەروەها : 'Add' لەگەڵ case 'add' یەکسان نییە. سەرەتا دەقەکە بە lowerـدا تێپەڕێنە و دەتوانێت Add، ADD یان add بنووسێت. ئەمە بۆ چوار کاری ژمێرکاری، بە دەقی:

A text menu (a sample run)مێنیوێکی دەقی (جارێک جێبەجێکردن)calculator.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
op = input('Operation (add, sub, mul, div): ', 's');
a = input('First number: ');
b = input('Second number: ');
r = NaN;                       % no result yet
switch lower(op)
    case 'add'
        r = a + b;
    case 'sub'
        r = a - b;
    case 'mul'
        r = a * b;
    case 'div'
        if b == 0
            disp('Cannot divide by zero')
        else
            r = a / b;
        end
    otherwise
        disp('Unknown operation')
end
if ~isnan(r)
    fprintf('%g %s %g = %g\n', a, op, b, r)
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The choice is text, so input needs 's'.

هەڵبژاردنەکە دەقە، بۆیە input پێویستی بە 's'ـە.

Lineدێڕی 4

NaN marks “no result yet”; it is tested with isnan at the end.

NaN نیشانەی «هێشتا ئەنجام نییە»یە؛ لە کۆتاییدا بە isnan دەپشکنرێت.

Lineدێڕی 13-17

An if inside a case: a switch and an if work well together.

ifـێک لەناو caseـێکدا: switch و if پێکەوە باش کار دەکەن.

Another run: dividing by zero is caughtجارێکی تر: دابەشکردن بەسەر سفردا دەگیرێت
Operation (add, sub, mul, div): div
First number: 5
Second number: 0
Cannot divide by zero
Quick checkپشکنینی خێراThe user types MUL. With switch lower(op), which case runs? دەنووسێت MUL. بە switch lower(op)، کام case جێبەجێ دەبێت؟

Switching on text: a small calculatorswitch لەسەر دەق: حاسیبەیەکی بچووک

Several values in one caseچەند نرخێک لە یەک caseـدا

To give several values the same action, list them in curly braces: case {6, 7} matches 6 or 7, and case {'sat', 'sun'} matches either text. The braces build what MATLAB calls a cell array; MathWorks says a cell-array case matches when any one of its elements matches. In the Kurdistan Region the weekend is Friday and Saturday — days 6 and 7 in the lab's numbering:

بۆ ئەوەی چەند هەمان کار وەربگرن، لەناو کەوانەی لووتکەداردا لیستیان بکە: case {6, 7} لەگەڵ 6 یان 7 یەکسان دەبێت و case {'sat', 'sun'} لەگەڵ هەر یەکێک لە دوو دەقەکە. کەوانەکان ئەوە دروست دەکەن کە MATLAB پێی دەڵێت ⁦cell array⁩؛ MathWorks دەڵێت caseـێکی ⁦cell array⁩ کاتێک یەکسان دەبێت کە هەر یەکێک لە یەکسان بێت. لە هەرێمی کوردستاندا پشووی کۆتایی هەفتە هەینی و شەممەیە — ڕۆژەکانی 6 و 7 بە ژماردنی تاقیگەکە:

Two groups of daysدوو کۆمەڵەی ڕۆژMATLABType in a terminalلە تێرمیناڵدا بینووسە
day = input('Day number (1-7): ');
switch day
    case {1, 2, 3, 4, 5}
        disp('Working day')
    case {6, 7}
        disp('Weekend')
    otherwise
        disp('Unknown day number')
end
Quick checkپشکنینی خێراWhich case matches both 'y' and 'yes'?کام case لەگەڵ هەردوو 'y' و 'yes' یەکسان دەبێت؟

From a mark to a grade with fixلە نمرەوە بۆ پلە بە fix

A switch compares equal values, but marks come in ranges: 90–100 is A, 80–89 is B, and so on. The lab's trick turns each range into one value: fix(mark/10) divides by 10 and cuts off the decimals (fix rounds toward zero), so 87→8.7→887 \to 8.7 \to 8 and 79.5→7.95→779.5 \to 7.95 \to 7. Each group of ten marks becomes one whole number, and that number can be a case. Here is the lab's program:

switch بەراورد دەکات، بەڵام پلەکان بەپێی دەدرێن: ⁦90–100⁩ دەبێتە A، ⁦80–89⁩ دەبێتە B و هتد. فێڵەکەی تاقیگە هەر دەکات بە یەک : fix(mark/10) بەسەر ⁦10⁩دا دابەش دەکات و ژمارەکانی دوای دەبڕێت (fix بەرەو سفر نزیک دەکاتەوە)، بۆیە 87→8.7→887 \to 8.7 \to 8 و 79.5→7.95→779.5 \to 7.95 \to 7. هەر کۆمەڵەیەکی دە نمرەیی دەبێتە یەک و ئەو ژمارەیە دەتوانێت case بێت. ئەمە تاقیگەکەیە:

The lab's grade program (run with 80)بەرنامەی پلەی تاقیگە (جێبەجێکردن بە ⁦80⁩)MATLABType in a terminalلە تێرمیناڵدا بینووسە
a = input('enter your mark:');
m = fix(a/10);
switch (m)
    case 9
        disp('A')
    case 8
        disp('B')
    case 7
        disp('C')
    case 6
        disp('D')
    case 5
        disp('E')
    otherwise
        disp('F')
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

fix(80/10) is 8.

fix(80/10) دەکاتە 8.

Lineدێڕی 3

Brackets around the switch value are allowed but not needed.

کەوانە لە دەوری switch ڕێگەپێدراوە بەڵام پێویست نییە.

Watch four marks go through it. Three of them land correctly; the fourth, a perfect 100, does not:

سەیری چوار نمرە بکە کە پێیدا تێدەپەڕن. سێیان بە دروستی دەگەن؛ چوارەمیان، ⁦100⁩ـی تەواو، ناگات:

Animation in seven frames. A mark goes into fix(mark/10), which gives a group number, and the group drops onto a row of cases: case 9 → A, case 8 → B, case 7 → C, case 6 → D, case 5 → E, otherwise → F. 95 gives group 9 and lands on A; 80 gives 8 and lands on B; 59 gives 5 and lands on E. 100 gives group 10, no case matches, and it slides to otherwise → F, shown in red. Then the first case is changed to case {9, 10} and 100 now lands on A, shown in green. The last frame lists the results 95 A, 80 B, 59 E, 100 A and asks to test every boundary: 100, 90, 89.9, 50, 49.9, 0.
Animation in seven frames. A mark goes into fix(mark/10), which gives a group number, and the group drops onto a row of cases: case 9 → A, case 8 → B, case 7 → C, case 6 → D, case 5 → E, otherwise → F. 95 gives group 9 and lands on A; 80 gives 8 and lands on B; 59 gives 5 and lands on E. 100 gives group 10, no case matches, and it slides to otherwise → F, shown in red. Then the first case is changed to case {9, 10} and 100 now lands on A, shown in green. The last frame lists the results 95 A, 80 B, 59 E, 100 A and asks to test every boundary: 100, 90, 89.9, 50, 49.9, 0.
Marks dropping through the switch: 100 → F, then the fixنمرەکان بە switchـدا دەکەون: ⁦100⁩ دەبێتە F، پاشان چاککردنەکەCêIT
Quick checkپشکنینی خێراWhy does the lab program print F for a mark of 100?بۆچی تاقیگە بۆ نمرەی ⁦100 F⁩ چاپ دەکات؟

From a mark to a grade with fixلە نمرەوە بۆ پلە بە fix

Two lab versions, one shared bugدوو وەشانی تاقیگە، یەک باگی هاوبەش

Mark → group → case → grade, for the two lab versions and the corrected programنمرە، کۆمەڵە، case و پلە بۆ دوو وەشانەکەی تاقیگە و
Markنمرەfix(mark/10)lab program تاقیگەQ3 versionوەشانی ⁦Q3⁩correctedچاککراو
959AaA
808BbB
79.57CcC
595Eun knownE
10010Fun knownA
49.54Fun knownF
00Fun knownF
−5-50Fun knownInvalid mark
10510Fun knownInvalid mark

A second lab question (Q3) does the same with lower-case letters 'a' to 'd' and puts every mark below 60 into otherwise, which prints 'un known' — a strange message for a failing mark, and its variable name stavarege and prompt “give me the rank of student” do not say what is typed. Both versions share the real bug in the table: a perfect 100 gets no A — F in the lab program, 'un known' in Q3 — because fix(100/10) is 10 and no case is 10. Both also accept impossible marks such as −5-5 or 105.

پرسیارێکی تری تاقیگە ⁦(Q3)⁩ هەمان کار بە پیتی بچووکی 'a' تا 'd' دەکات و هەموو نمرەیەکی خوار ⁦60⁩ دەخاتە otherwise، کە 'un known' چاپ دەکات — پەیامێکی سەیر بۆ نمرەیەکی دەرنەچوو. ناوی stavarege و «⁦give me the rank of student⁩» نالێن چی دەنووسرێت. هەردوو وەشانەکە هەمان ڕاستەقینەی ناو خشتەکەیان تێدایە: نمرەی تەواوی ⁦100⁩ پلەی A وەرناگرێت — لە تاقیگەدا F و لە ⁦Q3⁩ـدا 'un known' — چونکە fix(100/10) دەکاتە ⁦10⁩ و هیچ case نییە بۆ ⁦10⁩. هەردووکیان نمرەی مەحاڵی وەک −5-5 یان ⁦105⁩ـیش قبووڵ دەکەن.

Quick checkپشکنینی خێراWhat does the Q3 version print for a mark of 59?وەشانی ⁦Q3⁩ بۆ نمرەی ⁦59⁩ چی چاپ دەکات؟

From a mark to a grade with fixلە نمرەوە بۆ پلە بە fix

One corrected grade programبەرنامەیەکی چاککراو بۆ پلە

One corrected program replaces both lab versions. It first rejects marks outside 0–100 with an if (a switch cannot test a range), then switches on fix(mark/10) with case {9, 10} for A, and prints a clear sentence:

چاککراو جێگەی هەردوو وەشانەکەی تاقیگە دەگرێتەوە. سەرەتا بە if نمرەکانی دەرەوەی ⁦0–100⁩ ڕەت دەکاتەوە (switch ناتوانێت بپشکنێت)، پاشان لەسەر fix(mark/10) switch دەکات بە case {9, 10} بۆ A و ڕستەیەکی ڕوون چاپ دەکات:

grade.m (a sample run)⁦grade.m⁩ (جارێک جێبەجێکردن)grade.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
% grade.m - letter grade from a mark between 0 and 100
mark = input('Mark (0-100): ');
if mark < 0 || mark > 100
    disp('Invalid mark')
else
    switch fix(mark/10)
        case {9, 10}
            grade = 'A';
        case 8
            grade = 'B';
        case 7
            grade = 'C';
        case 6
            grade = 'D';
        case 5
            grade = 'E';
        otherwise
            grade = 'F';
    end
    fprintf('Mark %g gives grade %s\n', mark, grade)
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

|| because each side is one true/false value.

|| چونکە هەر لایەک یەک ڕاست/هەڵەیە.

Lineدێڕی 7

100 → group 10 → A.

⁦100⁩ دەچێتە کۆمەڵەی ⁦10⁩ و A وەردەگرێت.

Lineدێڕی 20

%g prints 79.5 without extra zeros.

%g ژمارەی ⁦79.5⁩ بێ سفری زیادە چاپ دەکات.

Test at the boundaries, where mistakes hide: 100, 90, 89.9, 50, 49.9 and 0, plus one impossible mark on each side. The Python track writes the same job with if/elif (a clean grade program).

لە سنوورەکاندا تاقی بکەرەوە، کە هەڵەکان لەوێ خۆیان دەشارنەوە: ⁦100⁩، ⁦90⁩، ⁦89.9⁩، ⁦50⁩، ⁦49.9⁩ و 0، لەگەڵ نمرەیەکی مەحاڵ لە هەر لایەک. بەشی Python هەمان کار بە if/elif دەنووسێت (بەرنامەیەکی پلەی ڕێکوپێک).

Quick checkپشکنینی خێراWith the corrected program, what is printed for the mark 89.9?بە ، بۆ نمرەی ⁦89.9⁩ چی چاپ دەکرێت؟

Another range trick: salary classesفێڵێکی تری ماوەکان: پۆلەکانی مووچە

A third lab program puts a monthly salary into a class with the same idea: fix(s/100) turns 100–199 into 1, 200–299 into 2, and so on. Here the salary is in thousands of dinars, so 150 means 150,000 IQD:

سێیەم تاقیگە بە هەمان بیرۆکە مووچەی مانگانە دەخاتە پۆلێکەوە: fix(s/100) ⁦100–199⁩ دەکات بە 1، ⁦200–299⁩ بە 2 و هتد. لێرەدا مووچەکە بە هەزار دینارە، بۆیە ⁦150⁩ واتە ⁦150,000⁩ دینار:

Salary classes (run with 250)پۆلەکانی مووچە (جێبەجێکردن بە ⁦250⁩)salary_class.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
s = input('Monthly salary (thousand IQD): ');
switch fix(s/100)
    case 1
        disp('C')
    case 2
        disp('B')
    case 3
        disp('A')
    case 4
        disp('A+')
    otherwise
        disp('undefined')
end
The lab's test values, plus the boundaries 100 and 499 تاقیکردنەوەی تاقیگە، لەگەڵ سنوورەکانی ⁦100⁩ و ⁦499⁩
Salaryمووچەfix(s/100)Classپۆل
1501C
2502B
3993A
4504A+
990undefined
5005undefined
1001C
4994A+

The test values were chosen well: 399 and 450 sit near the top of their groups, and 99 and 500 lie just outside the defined range, so they go to otherwise. Adding 100 and 499 tests the exact edges. The program does not check for negative salaries; that would again need an if before the switch.

تاقیکردنەوە بە باشی هەڵبژێردراون: ⁦399⁩ و ⁦450⁩ لە نزیک سەرەوەی کۆمەڵەکانیانن. ⁦99⁩ و ⁦500⁩ـیش ڕێک دەکەونە دەرەوەی ، بۆیە دەچن بۆ otherwise. زیادکردنی ⁦100⁩ و ⁦499⁩ لێوارە ڕێکەکان تاقی دەکاتەوە. مووچەی سالب ناپشکنێت؛ ئەوە دووبارە پێویستی بە ifـێکە پێش switch.

Quick checkپشکنینی خێراWhich class does a salary of 300 get?مووچەی ⁦300⁩ کام پۆل وەردەگرێت؟

switch or if?switch یان if؟

Use switch when one value is compared with a list of fixed values — numbers or texts. Use if when you need ranges, several variables, or conditions such as x > 0 && y > 0. A tempting mistake is to put a comparison into a case. MathWorks advises against relational operators such as < or > in a case expression, and the example shows why:

switch بەکار بهێنە کاتێک یەک لەگەڵ چەند جێگیر بەراورد دەکرێت — ژمارە یان دەق. if بەکار بهێنە کاتێک ، چەند یان وەک x > 0 && y > 0ـت پێویستە. هەڵەیەکی سەرنجڕاکێش ئەوەیە بەراوردێک بخەیتە ناو caseـەوە. MathWorks ئامۆژگاری دەکات کە وەک < یان > لە caseـدا بەکار نەهێنرێن و نموونەکە پیشان دەدات بۆچی:

A comparison inside a case: wrongبەراوردێک لەناو caseـدا: هەڵەMATLABType in a terminalلە تێرمیناڵدا بینووسە
mark = 95;
switch mark
    case mark >= 90
        disp('A')
    otherwise
        disp('F')
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

mark >= 90 is worked out first and gives 1. MATLAB then asks: is 95 equal to 1? No — so otherwise prints F.

سەرەتا mark >= 90 هەژمار دەکرێت و 1 دەدات. پاشان MATLAB دەپرسێت: ئایا ⁦95⁩ یەکسانە بە 1؟ نەخێر — بۆیە otherwise F چاپ دەکات.

Choosing between switch and ifهەڵبژاردن لە نێوان switch و if
Featureتایبەتمەندیswitchif / elseif
comparesبەراورد دەکاتone value for equalityیەک بۆ یەکسانبوونany conditionهەر
rangesonly with a trick such as fix(mark/10)تەنها بە فێڵێکی وەک fix(mark/10)directly: mark >= 90ڕاستەوخۆ: mark >= 90
textدەقexact match, like strcmpیەکسانبوونی تەواو، وەک strcmpneeds strcmpپێویستی بە strcmpـە
several valuesچەند case {6, 7}case {6, 7}d == 6 || d == 7d == 6 || d == 7

If you know Python: since Python 3.10 its match statement plays the role of switch (match).

ئەگەر Python دەزانیت: لە ⁦Python 3.10⁩ـەوە match ڕۆڵی switch دەگێڕێت (match).

Quick checkپشکنینی خێراWhich job suits a switch best?کام کار باشترین گونجاوە بۆ switch؟

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوودەداتFixچارەسەر
Expecting fall-through (C, Java habit) and adding breakچاوەڕوانیی (ڕاهاتنی C و Java) و زیادکردنی breakNot needed: only the first matching case runs. (break belongs to loops.)پێویست نییە: تەنها یەکەم caseـی یەکسان جێبەجێ دەبێت. (break سەر بە .)Leave break out of a switch.break لە switch لاببە.
case 9, 10 without bracescase 9, 10 بەبێ کەوانەOnly 9 matches; 10 becomes a statement that prints ans = 10.تەنها 9 یەکسان دەبێت؛ 10 دەبێتە کە ans = 10 چاپ دەکات.case {9, 10}case {9, 10}
case mark >= 90case mark >= 90Compares the switch value with 0 or 1. switch لەگەڵ 0 یان 1 بەراورد دەکات.Use if, or a value trick such as fix(mark/10).if بەکار بهێنە، یان فێڵێکی وەک fix(mark/10).
Misspelt or wrongly cased text cases: case 'Add' for input addcaseـی دەقی بە ڕێنووس یان قەبارەی پیتی هەڵە: case 'Add' بۆ addNo match; otherwise runs.یەکسانبوون نییە؛ otherwise جێبەجێ دەبێت.switch lower(op) and lower-case cases.switch lower(op) و caseـی پیت بچووک.
No otherwiseotherwise نییەUnexpected values pass silently. بە بێدەنگی تێدەپەڕن.Add an otherwise with a clear message.otherwiseـێک بە پەیامێکی ڕوون زیاد بکە.
Forgetting the 100-mark caseلەبیرچوونی caseـی نمرەی ⁦100⁩100 → F.⁦100⁩ دەبێتە F.case {9, 10}, and test the boundaries.case {9, 10} و سنوورەکان تاقی بکەرەوە.
A switch value that is a vector, e.g. switch [1 2] switch کە ، بۆ نموونە switch [1 2]An error: the value must be one number or one text.: دەبێت یەک ژمارە یان یەک دەق بێت.Switch on one element, or use if with any/all.لەسەر یەک switch بکە، یان if لەگەڵ any/all بەکار بهێنە.

Practiceڕاهێنان

ExerciseڕاهێنانDays in a monthڕۆژەکانی مانگێک

Read a month number and print how many days it has (February: 28). Use cell-array cases for the 30-day and 31-day months.

ژمارەی مانگێک بخوێنەوە و چاپ بکە چەند ڕۆژی هەیە (شوبات: ⁦28⁩). بۆ مانگە ⁦30⁩ و ⁦31⁩ ڕۆژییەکان caseـی ⁦cell array⁩ بەکار بهێنە.

Hintئاماژە

Three groups: {2}, {4, 6, 9, 11} and the seven 31-day months.

سێ کۆمەڵە: {2}، {4، 6، 9، ⁦11⁩} و حەوت مانگە ⁦31⁩ ڕۆژییەکە.

Show answerوەڵامەکە پیشان بدە
month_days.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
m = input('Month number (1-12): ');
switch m
    case 2
        days = 28;
    case {4, 6, 9, 11}
        days = 30;
    case {1, 3, 5, 7, 8, 10, 12}
        days = 31;
    otherwise
        days = 0;
end
if days == 0
    disp('Unknown month')
else
    fprintf('Month %d has %d days\n', m, days)
end

In a leap year February has 29 days — combine this program with the leap-year test of the conditions lesson.

لە ساڵی کەبیسەدا شوبات ⁦29⁩ ڕۆژە — ئەم لەگەڵ پشکنینی ساڵی کەبیسەی وانەی مەرجەکان تێکەڵ بکە.

ExerciseڕاهێنانVowel or consonantپیتی بزوێن یان نەبزوێن

Read one English letter as text and print whether it is a vowel (a, e, i, o, u) or not. Accept capital letters too.

یەک پیتی ئینگلیزی وەک دەق بخوێنەوە و چاپ بکە کە بزوێنە (a، e، i، o، u) یان نا. پیتی گەورەش قبووڵ بکە.

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
c = input('One letter: ', 's');
switch lower(c)
    case {'a', 'e', 'i', 'o', 'u'}
        disp('vowel')
    otherwise
        disp('not a vowel')
end
ExerciseڕاهێنانPredict the outputدەرخستە پێشبینی بکە

For the corrected grade.m, what is printed for 50, 49.9, 100 and 101?

بۆ grade.mـی چاککراو، بۆ ⁦50⁩، ⁦49.9⁩، ⁦100⁩ و ⁦101⁩ چی چاپ دەکرێت؟

Show answerوەڵامەکە پیشان بدە

50 → Mark 50 gives grade E; 49.9 → Mark 49.9 gives grade F (fix(4.99) is 4); 100 → Mark 100 gives grade A; 101 → Invalid mark.

بۆ ⁦50⁩: Mark 50 gives grade E؛ بۆ ⁦49.9⁩: Mark 49.9 gives grade F (fix(4.99) دەکاتە ⁦4⁩)؛ بۆ ⁦100⁩: Mark 100 gives grade A؛ بۆ ⁦101⁩: Invalid mark.

ExerciseڕاهێنانFrom if to switchلە ifـەوە بۆ switch

Rewrite with a switch: if c == 1 disp('Erbil'), elseif c == 2 disp('Sulaymaniyah'), elseif c == 3 disp('Duhok'), else disp('other city'), end

بە switch دووبارە بینووسەوە: if c == 1 disp('Erbil'), elseif c == 2 disp('Sulaymaniyah'), elseif c == 3 disp('Duhok'), else disp('other city'), end

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
switch c
    case 1
        disp('Erbil')
    case 2
        disp('Sulaymaniyah')
    case 3
        disp('Duhok')
    otherwise
        disp('other city')
end
ExerciseڕاهێنانSalary boundariesسنوورەکانی مووچە

Which class do the salaries 199, 200 and 400 get in the salary program? Which salaries between 0 and 600 are undefined?

مووچەکانی ⁦199⁩، ⁦200⁩ و ⁦400⁩ لە مووچەدا کام پۆل وەردەگرن؟ کام مووچانە لە نێوان 0 و ⁦600⁩دا undefinedن؟

Show answerوەڵامەکە پیشان بدە

199 → C (fix(1.99) is 1); 200 → B; 400 → A+. Undefined: every salary below 100 and every salary of 500 or more.

⁦199⁩ دەبێتە C (fix(1.99) دەکاتە ⁦1⁩)؛ ⁦200⁩ دەبێتە B؛ ⁦400⁩ دەبێتە ⁦A+. undefined⁩: هەموو مووچەیەکی خوار ⁦100⁩ و هەموو مووچەیەکی ⁦500⁩ و سەرووتر.

Summaryکورتە

  • switch compares one value (a number or a text) with each case from the top; the first match runs and the switch ends — no fall-through, no break needed.
  • otherwise catches unmatched values; it is optional but good practice.
  • Text cases match exactly and are case-sensitive; switch lower(op) accepts any capitals.
  • case {6, 7} (a cell array) gives several values one action; case 6, 7 does not.
  • fix(mark/10) turns ranges into values; remember case {9, 10} for 100 and reject impossible marks with an if first.
  • Ranges and combined conditions belong to if; never write a comparison inside a case.
  • switch یەک (ژمارە یان دەق) لە سەرەوە لەگەڵ هەر caseـێک بەراورد دەکات؛ یەکەم یەکسانبوون جێبەجێ دەبێت و switch کۆتایی دێت — بێ ، بێ پێویستی بە break.
  • otherwise ئەو یەکسان نین دەگرێت؛ ئارەزوومەندانەیە بەڵام ڕاهاتنێکی باشە.
  • caseـی دەقی تەواو یەکسان دەبن و ؛ switch lower(op) هەر قەبارەیەکی پیت قبووڵ دەکات.
  • case {6, 7} ⁦(cell array)⁩ چەند یەک کار دەدات؛ case 6, 7 وا ناکات.
  • fix(mark/10) هەر دەکات بە یەک ؛ case {9, 10} بۆ ⁦100⁩ لە بیر بێت و سەرەتا بە if نمرەی مەحاڵ ڕەت بکەرەوە.
  • و سەر بە ifن؛ هەرگیز بەراورد لەناو caseـدا مەنووسە.
Review questionsپرسیارەکانی پێداچوونەوە
What does MATLAB print for switch 3, case {1, 3}, disp('odd'), case 3, disp('three'), end?MATLAB بۆ switch 3, case {1, 3}, disp('odd'), case 3, disp('three'), end چی چاپ دەکات؟

Only odd: the first matching case runs and the switch ends.

تەنها odd: یەکەم caseـی یەکسان جێبەجێ دەبێت و switch کۆتایی دێت.

Why reject marks outside 0–100 before the switch?بۆچی پێش switch نمرەکانی دەرەوەی ⁦0–100⁩ ڕەت دەکەینەوە؟

A switch cannot test ranges, and fix(105/10) is 10, which would wrongly give A.

switch ناتوانێت بپشکنێت و fix(105/10) دەکاتە ⁦10⁩، کە بە هەڵە A دەدات.

How do you make a text switch accept Yes, YES and yes?چۆن switchـێکی دەقی وا لێدەکەیت Yes، YES و yes قبووڵ بکات؟

Switch on lower(answer) and write the case in lower case: case 'yes'.

لەسەر lower(answer) switch بکە و caseـەکە بە پیتی بچووک بنووسە: case 'yes'.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

for Loops: Sums, Series and Searchingخولەکانی for: کۆکردنەوە، زنجیرە و گەڕان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.