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

while Loops, break and continueخولەکانی while، break و continue

Repeat code until something happens: the while loop and its three parts (start value, condition, change), the lab's endless loops and how Ctrl+C stops them, a sum too big to be exact, stopping at a negative input, loops with an unknown number of turns, break (with the lab's average-after-break bug and the ask-again pattern), continue, and when to choose for or while.

کۆد دووبارە بکەرەوە تا شتێک ڕوو دەدات: و سێ بەشەکەی ( سەرەتا، ، گۆڕان)، تاقیگە و چۆن ⁦Ctrl+C⁩ دەیانوەستێنێت، کۆیەک گەورەتر لەوەی ورد بێت، وەستان لەسەر سالب، کە ژمارەی جارەکانیان نەزانراوە، break ( دوای break و شێوازی دووبارە پرسین)، continue و کەی for یان while هەڵبژێریت.

25 min read25 خولەک خوێندنەوە · 21 stepsهەنگاو

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

  • Write a while loop with a start value, a condition and a change, and predict how many times its body runs.
  • Find the missing change in an infinite loop with a trace table, and stop a running program with Ctrl+C.
  • End an input loop with a sentinel value and validate input with while true … break.
  • Use break and continue correctly, including the count after break and the innermost-loop rule.
  • Choose between for and while, and explain why huge factorials are rounded.
  • بە سەرەتا، و گۆڕانێک بنووسیت و پێشبینی بکەیت جەستەکەی چەند جار جێبەجێ دەبێت.
  • گۆڕانی ونبوو لە بە بدۆزیتەوە و کە کار دەکات بە ⁦Ctrl+C⁩ بوەستێنیت.
  • بە کۆتایی پێ بهێنیت و بە ⁦while true⁩ … break بپشکنیت.
  • break و continue بە دروستی بەکار بهێنیت، ژماردن دوای break و یاسای ناوەکیترین .
  • لە نێوان for و whileـدا هەڵبژێریت و ڕوونی بکەیتەوە بۆچی نزیک دەکرێنەوە.

Repeating until something happensدووبارەکردنەوە تا شتێک ڕوو دەدات

A for loop is the right tool when you know the number of turns: ten marks, five terms of a series. Very often you do not know it in advance. Keep asking until the user types a negative number. Keep doubling until the amount passes 1000. Keep halving until the answer is accurate enough. For jobs like these MATLAB has the : it repeats a block of code as long as a is true and stops the first time the condition is false.

خولی for ئامرازی گونجاوە کاتێک ژمارەی جارەکان دەزانیت: دە نمرە، پێنج بڕگەی زنجیرەیەک. بەڵام زۆر جار ئەو ژمارەیە پێشوەختە نازانیت. بپرسە تا دەنووسێت. دوو هێندە بکە تا بڕەکە لە ⁦1000⁩ تێدەپەڕێت. نیوە بکە تا وەڵامەکە بەس وردە. بۆ کاری لەم جۆرە MATLAB هەیە: بلۆکێک کۆد دووبارە دەکاتەوە مادام ڕاست بێت و یەکەم جار کە هەڵە بوو، دەوەستێت.

The shared taxi at the garageتاکسیی هاوبەش لە گەراج

A shared taxi from Erbil to Sulaymaniyah waits at the garage while a seat is empty. Each new passenger fills one seat. The moment no seat is empty, the driver leaves. The waiting is the loop, a seat is empty is the condition, and each passenger is the change that brings the end closer.

تاکسییەکی هاوبەشی هەولێر بۆ سلێمانی لە گەراج چاوەڕێ دەکات مادام کورسییەکی بەتاڵ هەبێت. هەر سەرنشینێکی نوێ کورسییەک پڕ دەکاتەوە. هەر کە هیچ کورسییەکی بەتاڵ نەما، شۆفێرەکە دەڕوات. چاوەڕوانییەکە ، کورسییەکی بەتاڵ هەیە و هەر سەرنشینێک ئەو گۆڕانەیە کە کۆتایی نزیک دەکاتەوە.

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

The driver looks at the seats all the time. MATLAB tests the condition only at the top of each turn, so the whole body runs even if the condition becomes false halfway through it.

شۆفێرەکە هەموو کاتێک سەیری کورسییەکان دەکات. MATLAB تەنها لە سەرەتای هەر جارێکدا تاقی دەکاتەوە، بۆیە هەموو جێبەجێ دەبێت تەنانەت ئەگەر لە نیوەیدا هەڵە بێت.

Quick checkپشکنینی خێراWhen does a while loop stop? کەی دەوەستێت؟

Repeating until something happensدووبارەکردنەوە تا شتێک ڕوو دەدات

A first while loopیەکەم خولی while

Repetition is the same idea in every language (see the building blocks of algorithms); this lesson teaches MATLAB's form, break and continue. Every program here also runs in GNU Octave (free) and in the free version of MATLAB Online. A first example with new numbers: a lab sample starts with 3 cells and the number doubles every hour. After how many hours are there more than 1000 cells?

دووبارەکردنەوە لە هەموو زمانێکدا هەمان بیرۆکەیە (بڕوانە بەردە بناغەکانی ئەلگۆریزمەکان)؛ ئەم وانەیە شێوەی MATLAB و break و continue فێر دەکات. هەموو ئەم وانەیە لە ⁦GNU Octave⁩ (بەخۆڕایی) و وەشانی بەخۆڕایی ⁦MATLAB Online⁩ـیش کار دەکەن. یەکەم نموونە بە ژمارەی نوێ: نموونەیەکی تاقیگە بە 3 خانە دەست پێدەکات و ژمارەکەی هەموو کاتژمێرێک دوو هێندە دەبێت. دوای چەند کاتژمێر زیاتر لە ⁦1000⁩ خانە هەیە؟

Doubling until the amount passes 1000دوو هێندەکردن تا بڕەکە لە ⁦1000⁩ تێدەپەڕێتMATLABType in a terminalلە تێرمیناڵدا بینووسە
amount = 3;            % start value
hours = 0;
while amount <= 1000   % the condition
    amount = 2*amount; % the change
    hours = hours + 1;
end
fprintf('After %d hours: %d cells\n', hours, amount)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-2

The start values: 3 cells, 0 hours so far.

سەرەتا: 3 خانە، تا ئێستا 0 کاتژمێر.

Lineدێڕی 3

MATLAB tests amount <= 1000 before every turn.

MATLAB پێش هەموو جارێک amount <= 1000 تاقی دەکاتەوە.

Lineدێڕی 4-5

The body: double the amount and count one more hour.

: بڕەکە دوو هێندە بکە و کاتژمێرێکی تر بژمێرە.

Lineدێڕی 7

After end the loop is over: 3 → 6 → … → 768 → 1536, nine doublings.

دوای end تەواو دەبێت: 3 ← 6 ← … ← ⁦768⁩ ← ⁦1536⁩، نۆ جار دوو هێندەکردن.

Quick checkپشکنینی خێراIn the doubling example, what are hours and amount when the loop ends?لە نموونەی دوو هێندەکردندا، کاتێک تەواو دەبێت hours و amount چەندن؟

How a while loop runsخولی while چۆن جێبەجێ دەبێت

The form is short: the keyword while, a condition, the statements to repeat, and end.

شێوەکەی کورتە: while، ، ناو کە دووبارە دەبنەوە و end.

The shape of every while loopشێوەی هەموو خولێکی whileMATLAB
statements before the loop
while condition
    statements inside the loop
end
statements after the loop
  1. Testتاقیکردنەوە

    MATLAB works out the condition.

    MATLAB هەژمار دەکات.

  2. True: run the bodyڕاست: جەستەکە جێبەجێ بکە

    If it is true, every statement of the body runs once, then MATLAB goes back to the test.

    ئەگەر ڕاست بێت، هەموو یەک جار جێبەجێ دەبن، پاشان MATLAB دەگەڕێتەوە بۆ تاقیکردنەوەکە.

  3. False: leaveهەڵە: دەرچوون

    If it is false, MATLAB jumps to the first statement after end.

    ئەگەر هەڵە بێت، MATLAB باز دەدات بۆ یەکەم دوای end.

A flowchart. 'Start values' leads to a diamond 'condition true?'. The 'yes' arrow goes down to 'body' and then to a highlighted box 'change: bring the end closer', whose arrow loops back up to the diamond. The 'no' arrow goes right to 'statements after end'. A dashed orange arrow labelled 'break' leaves the body straight to 'statements after end'.هێڵکارییەکی ڕەوت. «نرخەکانی سەرەتا» دەچێتە ناو چوارگۆشەیەکی لار «مەرج ڕاستە؟». تیری «بەڵێ» دەچێتە خوارەوە بۆ «جەستە» و پاشان بۆ چوارگۆشەیەکی ڕەنگکراو «گۆڕان: کۆتایی نزیک بکەرەوە» کە تیرەکەی دەگەڕێتەوە بۆ سەرەوە بۆ چوارگۆشە لارەکە. تیری «نەخێر» دەچێت بۆ لای ڕاست بۆ «ڕستەکانی دوای end». تیرێکی پچڕپچڕی پرتەقاڵی بە ناوی «break» ڕاستەوخۆ لە جەستەکەوە دەچێت بۆ «ڕستەکانی دوای end».
The while loop as a flowchart: the change arrow must exist, and break is an emergency exit وەک : دەبێت تیری گۆڕان هەبێت و break دەرگای فریاکەوتنەCêIT

Two consequences. First, if the condition is false the very first time, the body runs zero times — with amount = 2000; in the example above, hours stays 0. Second, the condition follows the same truth rule as if: it is true only when it is not empty and every element is nonzero. A vector condition such as while v > 0 therefore means while all elements are positive; write all(…) or any(…) to say what you mean (see when the condition is an array). Join conditions with && and || (logical operators).

دوو ئەنجام. یەکەم، ئەگەر لە یەکەم جاردا هەڵە بێت، جەستەکە سفر جار جێبەجێ دەبێت — بە amount = 2000; لە نموونەکەی سەرەوەدا، hours بە 0 دەمێنێتەوە. دووەم، پەیڕەوی هەمان یاسای ڕاستیی if دەکات: تەنها کاتێک ڕاستە کە بەتاڵ نەبێت و هەموو ناسفر بن. بۆیە وەک while v > 0 واتە مادام هەموو موجەبن؛ all(…) یان any(…) بنووسە بۆ ئەوەی مەبەستەکەت ڕوون بێت (بڕوانە کاتێک مەرج ڕیزەکێکە). بە && و || پێکەوە ببەستە (کارپێکەرە لۆجیکییەکان).

Quick checkپشکنینی خێراamount = 2000; hours = 0; and then the doubling loop while amount <= 1000 … end. How many times does the body run?amount = 2000; hours = 0; و پاشان دوو هێندەکردن while amount <= 1000 … end. جەستەکە چەند جار جێبەجێ دەبێت؟

MATLAB Crash Course for BeginnersfreeCodeCamp.org · Englishئینگلیزی · 1.7M viewsبینین · 37K likesلایک · Partبەشی 1:45:54–1:50:16 (ofلە 1:57:45)

A MATLAB beginner course by Phil Parisi: the Command Window, variables, vectors and matrices, indexing, scripts, sections and naming rules, each in short parts.

کۆرسێکی سەرەتایی MATLAB لەلایەن ⁦Phil Parisi: Command Window⁩، ، و ، ، ، بەشەکان و یاساکانی ناونان، هەر یەکەیان بە بەشێکی کورت.

Chapter 'While Loop' (1:45:54-1:50:16): the condition is tested before each turn; once it is false the loop stops.

بەشی While Loop (لە ⁦1:45:54⁩ تا ⁦1:50:16⁩): پێش هەر دەپشکنرێت؛ هەر کە بوو بە false، دەوەستێت.

The three parts every while loop needsئەو سێ بەشەی هەموو خولێکی while پێویستی پێیانە

A while loop that works always has three parts. Two of them are easy to see; the third is the one people forget.

کە بە دروستی کار دەکات هەمیشە سێ بەشی هەیە. دووانیان بە ئاسانی دەبینرێن؛ سێیەمیان ئەوەیە کە خەڵک لە بیری دەکەن.

Start value, condition, change سەرەتا، ، گۆڕان
PartبەشWhereلە کوێIn the doubling exampleلە نموونەی دوو هێندەکردندا
Start value — the variables the condition uses get a value سەرەتا — بەکاریان دەهێنێت وەردەگرنbefore whileپێش whileamount = 3;
Condition — the question asked before every turn — ئەو پرسیارەی پێش هەموو جارێک دەکرێتafter the word whileدوای وشەی whileamount <= 1000
Change — something in the body moves the condition towards falseگۆڕان — شتێک لە جەستەکەدا بەرەو هەڵە دەباتinside the bodyلەناو جەستەکەداamount = 2*amount;

The change must also go in the right direction. amount = amount/2; changes the amount, but it moves it away from 1000, so the condition stays true for ever. When you write a while loop, point at the line that will one day make the condition false. If you cannot find that line, the loop has a bug.

گۆڕانەکە دەبێت بە ئاڕاستەی دروستیش بڕوات. amount = amount/2; بڕەکە دەگۆڕێت، بەڵام لە ⁦1000⁩ دووری دەخاتەوە، بۆیە بۆ هەمیشە ڕاست دەمێنێتەوە. کاتێک دەنووسیت، ئاماژە بەو دێڕە بکە کە ڕۆژێک هەڵە دەکات. ئەگەر نەتتوانی ئەو دێڕە بدۆزیتەوە، تێدایە.

Quick checkپشکنینی خێراWhich line is the change in this loop? k = 1; while k^2 < 50, disp(k^2), k = k + 1; endکام دێڕ گۆڕانەکەیە لەم ؟ k = 1; while k^2 < 50, disp(k^2), k = k + 1; end

Spot the mistake: a loop that never endsهەڵەکە بدۆزەرەوە: خولێک کە هەرگیز کۆتایی نایەت

This program comes from the course's lab sheet (re-typed; the bug is kept on purpose). It should add ten terms of a series with alternating signs: J flips between 1 and −1, and pow takes the odd powers 1, 3, 5, … Read it and look for the three parts of the loop.

ئەم لە پەڕەی تاقیگەی کۆرسەکەوە هاتووە (دووبارە نووسراوەتەوە؛ بە مەبەست هێڵراوەتەوە). دەبێت دە بڕگەی زنجیرەیەک بە هێمای گۆڕاو کۆ بکاتەوە: J لە نێوان 1 و −1-1دا دەگۆڕێت و pow توانە تاکەکانی 1، 3، 5، … وەردەگرێت. بیخوێنەرەوە و بەدوای سێ بەشەکەی بگەڕێ.

Lab program 2, as handed outبەرنامەی 2ـی تاقیگە، وەک خۆیMATLABType in a terminalلە تێرمیناڵدا بینووسە
x = input('x = ');
J = 1;
pow = 1;
y = 0;
counter = 1;
while counter <= 10
    y = y + J*(sin(x)^pow/pi^pow);
    J = -J;
    pow = pow + 2;
end
disp(y)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

Start value of the counter: 1.

سەرەتای : 1.

Lineدێڕی 6

Condition: counter <= 10.

: counter <= 10.

Lineدێڕی 7-9

The body changes y, J and pow — but never counter.

جەستەکە y، J و pow دەگۆڕێت — بەڵام هەرگیز counter ناگۆڕێت.

counter starts at 1 and nothing inside the loop changes it, so counter <= 10 is true at every test. The loop is an : MATLAB keeps working, never reaches disp(y), and the >> prompt does not come back. The value of y even settles near 0.2499 after a few turns, which makes the bug sneaky — the number is right, but the program never stops to show it.

counter بە 1 دەست پێدەکات و هیچ شتێک لەناو نایگۆڕێت، بۆیە counter <= 10 لە هەموو تاقیکردنەوەیەکدا ڕاستە. : MATLAB بەردەوام کار دەکات، هەرگیز ناگاتە disp(y) و >> ناگەڕێتەوە. y تەنانەت دوای چەند جارێک لە نزیک ⁦0.2499⁩ جێگیر دەبێت، ئەمەش فێڵاوی دەکات — ژمارەکە دروستە، بەڵام هەرگیز ناوەستێت بۆ ئەوەی پیشانی بدات.

Two trace tables side by side. Left, the buggy loop: turns 1 to 5 and then dots; counter is 1 in every row, pow grows 3, 5, 7, 9, 11, y is 0.2678, 0.2486, 0.2500, 0.2499, 0.2499, and the last row says 'never ends'. Right, the fixed loop: at the end of the turns counter is 2, 3, 4 … 10, 11, the test 11 <= 10 is false and the loop ends.دوو خشتەی بەدواداچوون لە تەنیشت یەک. لای چەپ، خولە هەڵەدارەکە: جارەکانی 1 تا 5 و پاشان خاڵ؛ counter لە هەموو ڕیزێکدا 1ـە، pow گەورە دەبێت 3، 5، 7، 9، 11، y بریتییە لە 0.2678، 0.2486، 0.2500، 0.2499، 0.2499 و دوایین ڕیز دەڵێت «هەرگیز کۆتایی نایەت». لای ڕاست، خولە چاککراوەکە: لە کۆتایی جارەکاندا counter دەبێتە 2، 3، 4 … 10، 11، تاقیکردنەوەی 11 <= 10 هەڵەیە و خولەکە تەواو دەبێت.
Tracing both versions: the counter column shows the bug at onceبەدواداچوونی هەردوو وەشانەکە: ستوونی counter یەکسەر پیشان دەداتCêIT

Spot the mistake: a loop that never endsهەڵەکە بدۆزەرەوە: خولێک کە هەرگیز کۆتایی نایەت

Stopping a running program: Ctrl+Cوەستاندنی بەرنامەیەک کە کار دەکات: ⁦Ctrl+C⁩

When a program seems stuck, click in the Command Window and press Ctrl+C (hold Ctrl, press C). MathWorks' page on while gives exactly this advice for a loop that never ends on its own. MATLAB stops the program, prints a short message about the interruption, and the >> prompt returns. The same works in Octave and in MATLAB Online. On a Mac it is also Ctrl+C, not Cmd+C.

کاتێک وا دیارە گیری خواردووە، لە ⁦Command Window⁩ کلیک بکە و ⁦Ctrl+C⁩ دابگرە (Ctrl ڕابگرە و C دابگرە). پەڕەی MathWorks دەربارەی while ڕێک ئەم ئامۆژگارییە بۆ دەدات کە خۆی هەرگیز کۆتایی نایەت. MATLAB دەوەستێنێت، پەیامێکی کورت دەربارەی پچڕاندنەکە چاپ دەکات و >> دەگەڕێتەوە. هەمان لە Octave و ⁦MATLAB Online⁩ـیشدا کار دەکات. لەسەر Macـیش ⁦Ctrl+C⁩ـە، نەک ⁦Cmd+C⁩.

Animation in eight frames. The buggy loop runs: the turn number climbs 1, 2, 3 and then 250, 251, while counter stays 1 and y flips between 0.2678, 0.2486 and 0.2500 before settling at 0.2499; the status says Busy. A red Ctrl+C key is pressed and the program stops. Then the fixed loop runs: counter climbs from 1 to 10, the test 11 <= 10 is false, the loop ends and disp(y) prints 0.2499.
Animation in eight frames. The buggy loop runs: the turn number climbs 1, 2, 3 and then 250, 251, while counter stays 1 and y flips between 0.2678, 0.2486 and 0.2500 before settling at 0.2499; the status says Busy. A red Ctrl+C key is pressed and the program stops. Then the fixed loop runs: counter climbs from 1 to 10, the test 11 <= 10 is false, the loop ends and disp(y) prints 0.2499.
The endless loop, Ctrl+C, and the fixed loop that ends after ten turns، ⁦Ctrl+C⁩ و کە دوای دە جار کۆتایی دێتCêIT
Quick checkپشکنینی خێراA program has printed nothing for a minute and the status says Busy. What should you do first? خولەکێکە هیچی چاپ نەکردووە و دەڵێت Busy. یەکەم جار چی بکەیت؟

Spot the mistake: a loop that never endsهەڵەکە بدۆزەرەوە: خولێک کە هەرگیز کۆتایی نایەت

The fix, and what the program computesچاککردنەکە و ئەوەی بەرنامەکە هەژماری دەکات

Lab program 2, fixedبەرنامەی 2ـی تاقیگە، چاککراوMATLABType in a terminalلە تێرمیناڵدا بینووسە
x = input('x = ');
J = 1;
pow = 1;
y = 0;
counter = 1;
while counter <= 10
    y = y + J*(sin(x)^pow/pi^pow);
    J = -J;
    pow = pow + 2;
    counter = counter + 1;   % the missing change
end
disp(y)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10

Now counter grows 1, 2, …, 10, 11; at 11 the test fails and the loop ends.

ئێستا counter گەورە دەبێت 1، 2، …، ⁦10⁩، ⁦11⁩؛ لە ⁦11⁩دا تاقیکردنەوەکە سەرناکەوێت و تەواو دەبێت.

With the change in place the loop runs exactly ten times and adds

بە بوونی گۆڕانەکە ڕێک دە جار جێبەجێ دەبێت و ئەمە کۆ دەکاتەوە

y=∑k=09(−1)k(sin⁡xπ)2k+1y=\sum_{k=0}^{9}(-1)^k\left(\frac{\sin x}{\pi}\right)^{2k+1}

For x=1x=1 the ratio is sin⁡(1)/π≈0.2678\sin(1)/\pi \approx 0.2678 and the sum is 0.2499 (checked with Python). J supplies the sign (−1)k(-1)^k and pow the power 2k+12k+1.

بۆ x=1x=1 ڕێژەکە sin⁡(1)/π≈0.2678\sin(1)/\pi \approx 0.2678ـە و کۆکە ⁦0.2499⁩ـە (بە Python پشکنراوە). J هێمای (−1)k(-1)^k دەدات و pow 2k+12k+1.

Notice that this loop has a fixed number of turns (ten), so a for loop is the more natural choice: for k = 0:9 changes k by itself and cannot forget its change. While loops are for the cases where the number of turns is unknown — the next screens show them.

سەرنج بدە کە ئەم ژمارەیەکی جێگیری جاری هەیە (دە)، بۆیە هەڵبژاردنێکی سروشتیترە: for k = 0:9 خۆی k دەگۆڕێت و ناتوانێت گۆڕانەکەی لە بیر بکات. بۆ ئەو حاڵەتانەن کە ژمارەی جارەکان نەزانراوە — شاشەکانی داهاتوو پیشانیان دەدەن.

Program 4: a sum too big to be exactبەرنامە 4: کۆیەک گەورەتر لەوەی ورد بێت

Lab program 4 has the same missing counter = counter + 1;. With the fix it adds ten factorials with alternating signs, 1!, 5!, 9!, …, 37! (seq grows by 4 each turn):

4ـی تاقیگە هەمان counter = counter + 1;ـی ونبووی هەیە. بە چاککردنەکە دە بە هێمای گۆڕاو کۆ دەکاتەوە، ⁦1!⁩، ⁦5!⁩، ⁦9!⁩، …، ⁦37!⁩ (seq هەموو جارێک 4 زیاد دەکات):

Lab program 4, fixedبەرنامەی 4ـی تاقیگە، چاککراوMATLABType in a terminalلە تێرمیناڵدا بینووسە
y = 0;
J = 1;
seq = 1;
counter = 1;
while counter <= 10
    y = y + J*factorial(seq);
    J = -J;
    seq = seq + 4;
    counter = counter + 1;   % added
end
disp(y)
y=∑k=09(−1)k (4k+1)!=1!−5!+9!−⋯−37!y=\sum_{k=0}^{9}(-1)^k\,(4k+1)!=1!-5!+9!-\cdots-37!

The last term, 37!≈1.376×104337! \approx 1.376\times 10^{43}, is so large that it decides the result.

دوایین بڕگە، 37!≈1.376×104337! \approx 1.376\times 10^{43}، ئەوەندە گەورەیە کە ئەنجامەکە دیاری دەکات.

The exact answer is a whole number with 44 digits: −13 763 744 407 917 567 980 912 064 812 596 549 260 002 039-13\,763\,744\,407\,917\,567\,980\,912\,064\,812\,596\,549\,260\,002\,039. MATLAB cannot hold it. A double stores every whole number exactly only up to 253≈9.007×10152^{53}\approx 9.007\times 10^{15}; MathWorks' page on factorial says the result is exact for n≤21n \le 21 and above that is right only in its first 15 digits. So MATLAB's −1.3764e+43 is a rounded answer: correct in its leading digits, wrong in the last ones. Read more in round-off, factorial and what computers cannot do exactly.

وەڵامە وردەکە بە ⁦44⁩ : −13 763 744 407 917 567 980 912 064 812 596 549 260 002 039-13\,763\,744\,407\,917\,567\,980\,912\,064\,812\,596\,549\,260\,002\,039. MATLAB ناتوانێت هەڵیبگرێت. double هەموو تەنها تا 253≈9.007×10152^{53}\approx 9.007\times 10^{15} بە وردی هەڵدەگرێت؛ پەڕەی MathWorks دەربارەی factorial دەڵێت ئەنجامەکە بۆ n≤21n \le 21 وردە و لەوە زیاتر تەنها لە ⁦15⁩ یەکەمیدا دروستە. بۆیە ⁦−1.3764e+43⁩ـی MATLAB وەڵامێکی نزیککراوەیە: لە دروستە، لە کۆتاییەکانیدا هەڵەیە. زیاتر بخوێنەرەوە لە هەڵەی نزیککردنەوە، فاکتۆریێل و ئەوەی کۆمپیوتەر ناتوانێت بە وردی بیکات.

Quick checkپشکنینی خێراWhy is MATLAB's answer to program 4 not exact?بۆچی وەڵامی MATLAB بۆ 4 ورد نییە؟

Stopping at a special inputوەستان لەسەر نێوخستەیەکی تایبەت

Lab program 3 reads a number, prints its factorial, and reads again — until the user types a negative number. The negative number is not data; it is a signal that means stop. Programmers call such a value a . Nobody knows in advance how many numbers will come, so this is a job for while.

3ـی تاقیگە ژمارەیەک دەخوێنێتەوە، چاپ دەکات و دووبارە دەخوێنێتەوە — تا ژمارەیەکی سالب دەنووسێت. نییە؛ نیشانەیەکە بە واتای بوەستە. بەرنامەنووسان بەم جۆرە دەڵێن . کەس پێشوەختە نازانێت چەند ژمارە دێت، بۆیە ئەمە کاری whileـە.

Lab program 3, as handed out (sample run: 4, 0, 6, −1)بەرنامەی 3ـی تاقیگە، وەک خۆی (نموونەی جێبەجێکردن: 4، 0، 6، −1-1)MATLABType in a terminalلە تێرمیناڵدا بینووسە
x = input('x = ');
while x >= 0
    y = factorial(x)
    x = input('x = ')
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Start value: the first number is read before the loop.

سەرەتا: یەکەم ژمارە پێش دەخوێندرێتەوە.

Lineدێڕی 3-4

No semicolons, so MATLAB echoes y = … and x = … after each input.

نییە، بۆیە MATLAB دوای هەر y = … و x = … پیشان دەداتەوە.

Lineدێڕی 4

The change: a new x from the user. A negative one makes x >= 0 false.

گۆڕانەکە: xـێکی نوێ لە . xـی سالب x >= 0 هەڵە دەکات.

The program works, but its output is noisy, and the original sheet also wrote while(x>=0); with a semicolon after the condition — MATLAB accepts that empty statement, but it only confuses the reader. A tidier version prints one clear line per number with fprintf (printing with fprintf):

کار دەکات، بەڵام قەرەباڵغە و پەڕە ڕەسەنەکە while(x>=0);ـیشی نووسیوە بە دوای — MATLAB ئەو وەردەگرێت، بەڵام تەنها خوێنەر سەرگەردان دەکات. وەشانێکی ڕێکتر بۆ هەر ژمارەیەک یەک دێڕی ڕوون بە fprintf چاپ دەکات (چاپکردن بە fprintf):

The same loop, tidiedهەمان خول، ڕێکخراوMATLABType in a terminalلە تێرمیناڵدا بینووسە
x = input('Whole number (negative to stop): ');
while x >= 0
    fprintf('%d! = %d\n', x, factorial(x))
    x = input('Whole number (negative to stop): ');
end
disp('Goodbye')
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The semicolon matters here: it stops MATLAB from echoing x.

لێرەدا گرنگە: ڕێگری دەکات لەوەی MATLAB x پیشان بداتەوە.

Quick checkپشکنینی خێراThe user's very first number is −3. What does the tidy program print?یەکەم ژمارەی −3-3ـە. چی چاپ دەکات؟

When nobody knows the number of turnsکاتێک کەس ژمارەی جارەکان نازانێت

The strength of while is a question whose answer is how many times? Hana's new page has 10,000 followers and grows by 25 % a month. Soran's page has 60,000 and gains 5,000 a month. After how many months does Hana catch up? Count the turns, and print the situation before and after the loop so you can check it:

هێزی while لە پرسیارێکدایە کە وەڵامەکەی چەند جار؟ـە. پەڕە نوێیەکەی هانا ⁦10,000⁩ شوێنکەوتووی هەیە و مانگانە ⁦25 %⁩ گەورە دەبێت. پەڕەکەی سۆران ⁦60,000⁩ـی هەیە و مانگانە ⁦5,000⁩ زیاد دەکات. دوای چەند مانگ هانا دەگاتە سۆران؟ جارەکان بژمێرە و دۆخەکە پێش و دوای چاپ بکە بۆ ئەوەی بتوانیت بیپشکنیت:

A catch-up race (new numbers)پێشبڕکێی گەیشتن (بە ژمارەی نوێ)MATLABType in a terminalلە تێرمیناڵدا بینووسە
hana = 10000;
soran = 60000;
months = 0;
fprintf('Before the loop: Hana %d, Soran %d\n', hana, soran)
while hana < soran
    hana = 1.25*hana;
    soran = soran + 5000;
    months = months + 1;
end
fprintf('After %d months: Hana %.0f, Soran %d\n', months, hana, soran)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

months is a : it starts at 0 and the body adds 1.

months : بە 0 دەست پێدەکات و جەستەکە 1ی بۆ زیاد دەکات.

Lineدێڕی 5

Both values change inside the loop; the condition compares them.

هەردوو لەناو دەگۆڕێن؛ بەراوردیان دەکات.

Lineدێڕی 10

%.0f prints Hana's 116415.32 without decimals.

%.0f ⁦116415.32⁩ـی هانا بێ چاپ دەکات.

Two more loops of the same kind (the guide shows the factorial one with 100; here with new numbers). The first finds the smallest n whose factorial is above 5000 — prod(1:n) multiplies 1⋅2⋯n1\cdot 2\cdots n. The second prints a running total until it passes 20:

دوو تر لە هەمان جۆر (ڕێبەرەکە نموونەی بە ⁦100⁩ پیشان دەدات؛ لێرە بە ژمارەی نوێ). یەکەمیان بچووکترین n دەدۆزێتەوە کە لە ⁦5000⁩ زیاترە — prod(1:n) 1⋅2⋯n1\cdot 2\cdots n لێک دەدات. دووەمیان کۆیەکی ڕۆیشتوو چاپ دەکات تا لە ⁦20⁩ تێدەپەڕێت:

Smallest nn with n!>5000n! > 5000بچووکترین nn کە n!>5000n! > 5000MATLABType in a terminalلە تێرمیناڵدا بینووسە
n = 1;
while prod(1:n) <= 5000
    n = n + 1;
end
n
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

6!=7206! = 720 is still too small; 7!=50407! = 5040 is the first above 5000.

6!=7206! = 720 هێشتا بچووکە؛ 7!=50407! = 5040 یەکەمە کە لە ⁦5000⁩ زیاترە.

A running total that stops after passing 20کۆیەکی ڕۆیشتوو کە دوای تێپەڕاندنی ⁦20⁩ دەوەستێتMATLABType in a terminalلە تێرمیناڵدا بینووسە
total = 0;
k = 0;
while total <= 20
    k = k + 1;
    total = total + k;
    fprintf('k = %d, total = %d\n', k, total)
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

total is an ; the line that grows it is also the change.

total ؛ ئەو دێڕەی گەورەی دەکات گۆڕانەکەشە.

Quick checkپشکنینی خێراIn the catch-up race, which value is the counter?لە پێشبڕکێی گەیشتندا، کام ؟

When nobody knows the number of turnsکاتێک کەس ژمارەی جارەکان نازانێت

Walking along a vector with an indexڕۆیشتن بە درێژایی ئاڕاستەبڕێک بە ئیندێکسێک

The guide also walks an index i along a vector with while and stops in time. Here is the idea with new data: find the first element above 50.

ڕێبەرەکە بە while i بە درێژایی دەجوڵێنێت و لە کاتی خۆیدا دەوەستێت. ئەمە بیرۆکەکەیە بە نوێ: یەکەم بدۆزەرەوە کە لە ⁦50⁩ زیاترە.

The first element above 50یەکەم توخم کە لە ⁦50⁩ زیاترەMATLABType in a terminalلە تێرمیناڵدا بینووسە
v = [12 47 33 58 91 20];
i = 1;
while i <= length(v) && v(i) <= 50
    i = i + 1;
end
fprintf('Element %d is %d\n', i, v(i))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

&& tests i <= length(v) first. If i has passed the end, it never looks at v(i), so there is no index error.

&& یەکەم جار i <= length(v) تاقی دەکاتەوە. ئەگەر i لە کۆتایی تێپەڕیبێت، هەرگیز سەیری v(i) ناکات، بۆیە ڕوو نادات.

This is the of && at work. With v = [12 47 33] the loop stops with i = 4, which is past the end — so check i <= length(v) before you use v(i) after the loop. The one-line MATLAB way is find(v > 50, 1) (comparing a whole vector).

ئەمە &&ـە لە کاردا. بە v = [12 47 33] بە ⁦i = 4⁩ دەوەستێت کە لە کۆتایی تێپەڕیوە — بۆیە پێش ئەوەی دوای v(i) بەکار بهێنیت، i <= length(v) بپشکنە. ڕێگای یەک دێڕیی MATLAB find(v > 50, 1)ـە (بەراوردکردنی ئاڕاستەبڕێکی تەواو).

Quick checkپشکنینی خێراWhy is i <= length(v) written before v(i) <= 50?بۆچی i <= length(v) پێش v(i) <= 50 نووسراوە؟

When nobody knows the number of turnsکاتێک کەس ژمارەی جارەکان نازانێت

Filling a vector step by stepپڕکردنەوەی ئاڕاستەبڕێک هەنگاو بە هەنگاو

The guide's first example on its second while page uses the same index walk to fill a vector. It makes x values from 0 to 2 in steps of h, a vector y of zeros with the same size (y = 0*x), sets y(1) = 1, and then computes every new element from the one before it, y(i+1) = y(i) + h*(…), until i reaches the last position, max(size(x)) — the same number as length(x). At the end it draws plot(x, y, 'go'). Here is the pattern with a short new rule: each new value lies halfway between the old value and x(i).

یەکەم نموونەی پەڕەی دووەمی whileـی ڕێبەرەکە هەمان ڕۆیشتنی بەکار دەهێنێت بۆ پڕکردنەوەی . x لە 0 تا 2 بە هەنگاوی h دروست دەکات، y لە سفر بە هەمان قەبارە (y = 0*x)، y(1) = 1 دادەنێت و پاشان هەر نوێ لە پێشوویەوە هەژمار دەکات، y(i+1) = y(i) + h*(…)، تا i دەگاتە دوایین شوێن، max(size(x)) — هەمان ژمارەی length(x). لە کۆتاییدا plot(x, y, 'go') دەکێشێت. ئەمە هەمان شێوازە بە یاسایەکی نوێی کورت: هەر نوێ لە نیوەڕێی نێوان و x(i)ـدایە.

Each new element from the one before itهەر توخمێکی نوێ لە توخمەکەی پێشوویەوەMATLABType in a terminalلە تێرمیناڵدا بینووسە
h = 0.5;
x = 0:h:2;              % 0  0.5  1  1.5  2
y = zeros(size(x));     % room for every value (the guide writes 0*x)
y(1) = 1;               % the start value
i = 1;
while i < length(x)     % the guide writes max(size(x))
    y(i+1) = y(i) + h*(x(i) - y(i));
    i = i + 1;
end
y
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

Make room for all the values before the loop, so MATLAB does not have to grow y at every turn.

پێش شوێن بۆ هەموو دابنێ ()، بۆ ئەوەی MATLAB ناچار نەبێت لە هەموو جارێکدا y گەورە بکات.

Lineدێڕی 6

< and not <=: the body writes y(i+1), so i must stop one before the last position.

< نەک <=: جەستەکە y(i+1) دەنووسێت، بۆیە دەبێت i یەک شوێن پێش کۆتایی بوەستێت.

Lineدێڕی 7

With h = 0.5 this is the average of y(i) and x(i): 1, 0.5, 0.5, 0.75, 1.125.

بە ⁦h = 0.5⁩ ئەمە ناوەندی y(i) و x(i)ـە: 1، ⁦0.5⁩، ⁦0.5⁩، ⁦0.75⁩، ⁦1.125⁩.

A rule that builds each value from the previous one is how computers follow anything that changes step by step — a balance month by month, or (in a numerical-analysis course) the solution of an equation of change. The loop is a while here because the guide wrote it so; since the number of turns is known (length(x) - 1), for i = 1:length(x)-1 does the same job.

یاسایەک کە هەر لە پێشوویەوە دروست دەکات، ڕێگای کۆمپیوتەرە بۆ بەدواداچوونی هەر شتێک کە هەنگاو بە هەنگاو دەگۆڕێت — بڕی پارەی هەژمارێکی بانک مانگ بە مانگ، یان (لە کۆرسێکی شیکاریی ژمارەییدا) چارەسەری گۆڕان. لێرەدا whileـە چونکە ڕێبەرەکە وای نووسیوە؛ بەڵام ژمارەی جارەکان زانراوە (length(x) - 1)، بۆیە for i = 1:length(x)-1 هەمان کار دەکات.

Quick checkپشکنینی خێراIn this loop, what goes wrong if the condition is i <= length(x)?لەم ، ئەگەر i <= length(x) بێت چی هەڵە دەبێت؟

break: leaving a loop at oncebreak: یەکسەر جێهێشتنی خولێک

Sometimes the reason to stop appears in the middle of the body. The ends the loop immediately: the rest of the body is skipped, no more turns happen, and MATLAB continues with the first statement after the loop's end. break works in for and while loops alike — MathWorks' page puts it simply: the statements after break in the loop do not run.

هەندێک جار هۆکاری وەستان لە ناوەڕاستی جەستەکەدا دەردەکەوێت. یەکسەر کۆتایی پێ دەهێنێت: باقیی جەستەکە باز دەدرێت، هیچ جارێکی تر ڕوو نادات و MATLAB بە یەکەم دوای endـی بەردەوام دەبێت. break لە for و whileـدا وەک یەک کار دەکات — پەڕەی MathWorks بە سادەیی دەڵێت: دوای break لە جێبەجێ نابن.

break: leaving a loop at oncebreak: یەکسەر جێهێشتنی خولێک

Spot the mistakes: the average after breakهەڵەکان بدۆزەرەوە: ناوەند دوای break

A lab program reads the marks of four subjects and stops at the first mark below 50. Then it prints the average. Here it is as it was typed in the lab (re-typed from a photo):

تاقیگە نمرەی چوار وانە دەخوێنێتەوە و لە یەکەم نمرەی خوار ⁦50⁩دا دەوەستێت. پاشان چاپ دەکات. ئەمە وەک ئەوەیە کە لە تاقیگەدا نووسراوە (لە وێنەیەکەوە دووبارە نووسراوەتەوە):

The lab's average program (three mistakes)بەرنامەی تاقیگە بۆ ناوەند (سێ هەڵە)MATLABType in a terminalلە تێرمیناڵدا بینووسە
sum = 0;
for i = 1:4
    n = input('inter the subject mark ');
    if n >= 50
        sum = sum + n;
    else
        break
    end
end
avg = sum/4

Marks 70 and 85 were added, then 40 triggered break. The program still divides by 4, so it reports 38.75 for a student whose two counted marks average 77.5. The three mistakes:

نمرەکانی ⁦70⁩ و ⁦85⁩ کۆ کرانەوە، پاشان ⁦40⁩ breakـی چالاک کرد. هێشتا دابەشی 4 دەکات، بۆیە ⁦38.75⁩ ڕادەگەیەنێت بۆ قوتابییەک کە دوو نمرە ژمێردراوەکەی ⁦77.5⁩ـە. سێ هەڵەکە:

  • Dividing by the planned count. After a break, fewer than four marks were added. Count the marks you really add and divide by that count.
  • A variable called sum. It hides MATLAB's own sum function for the rest of the session (the rule is explained in the accumulator). Call it total.
  • The prompt says inter. It should say Enter, and a colon and a space make the prompt easier to read.
  • دابەشکردن بە ژمارەی پلاندانراو. دوای break کەمتر لە چوار نمرە کۆ کرانەوە. ئەو نمرانە بژمێرە کە بەڕاستی کۆیان دەکەیتەوە و بەو ژمارەیە دابەشی بکە.
  • بە ناوی sum. بۆ باقیی کارەکەت sumـی خودی MATLAB دەشارێتەوە (یاساکە لە گۆڕاوی کۆکردنەوە ڕوون کراوەتەوە). ناوی بنێ total.
  • دەڵێت inter. دەبێت بڵێت Enter؛ دوو خاڵ و خوێندنەوەی ئاسانتر دەکەن.
The corrected programبەرنامە چاککراوەکەMATLABType in a terminalلە تێرمیناڵدا بینووسە
total = 0;
count = 0;
for i = 1:4
    mark = input('Enter the subject mark: ');
    if mark < 50
        break                  % leave the loop at once
    end
    total = total + mark;
    count = count + 1;
end
if count > 0
    avg = total/count
else
    disp('No marks were added.')
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

A second counter for the marks actually added.

دووەم بۆ ئەو نمرانەی بەڕاستی کۆ کراونەتەوە.

Lineدێڕی 11-15

If the very first mark is below 50, count is 0: say so instead of dividing by zero.

ئەگەر یەکەم نمرە لە خوار ⁦50⁩ بێت، count 0ـە: ئەوە بڵێ لە جیاتی دابەشکردن بە سفر.

Testing both programs (the third case is the edge case)تاقیکردنەوەی هەردوو (حاڵەتی سێیەم حاڵەتی لێوارە)
Marks typedنمرە نووسراوەکانLab program تاقیگەCorrected program
70, 85, 40avg = 38.7500avg = 77.5000
66, 74, 58, 90avg = 72avg = 72
30avg = 0No marks were added.
Quick checkپشکنینی خێراMarks 90, 45 are typed into the lab program. What does it print?نمرەکانی ⁦90⁩، ⁦45⁩ لە تاقیگەدا دەنووسرێن. چی چاپ دەکات؟

break: leaving a loop at oncebreak: یەکسەر جێهێشتنی خولێک

while true … break: ask until the answer is validwhile true … break: بپرسە تا وەڵامەکە دروست دەبێت

MATLAB has no , which runs its body first and tests afterwards. MathWorks' page on while shows the usual replacement: a loop whose condition is always true, with an if … break at the point where you can decide. It is ideal for checking input ():

MATLAB نییە کە یەکەم جار جەستەکەی جێبەجێ دەکات و پاشان تاقی دەکاتەوە. پەڕەی MathWorks دەربارەی while جێگرەوە باوەکە پیشان دەدات: کە هەمیشە trueـە و if … breakـێک لەو شوێنەی دەتوانیت بڕیار بدەیت. بۆ پشکنینی () زۆر گونجاوە:

Asking again until a mark is between 0 and 100دووبارە پرسین تا نمرەکە لە نێوان 0 و ⁦100⁩دا دەبێتMATLABType in a terminalلە تێرمیناڵدا بینووسە
while true
    mark = input('Mark (0-100): ');
    if mark >= 0 && mark <= 100
        break
    end
    disp('Please type a number from 0 to 100.')
end
fprintf('Saved mark: %d\n', mark)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

true never becomes false, so the only way out is break.

true هەرگیز هەڵە نابێت، بۆیە تاکە ڕێگای دەرچوون breakـە.

Lineدێڕی 3-5

The test sits after the input: a valid mark leaves the loop.

تاقیکردنەوەکە دوای دێت: نمرەیەکی دروست جێدەهێڵێت.

Quick checkپشکنینی خێراWhat makes a while true loop end?چی while true کۆتایی پێ دەهێنێت؟

break: leaving a loop at oncebreak: یەکسەر جێهێشتنی خولێک

break leaves only the innermost loopbreak تەنها ناوەکیترین خول جێدەهێڵێت

In a , break ends only the loop it is written in. The outer loop carries on with its next turn:

لە break تەنها ئەو کۆتایی پێ دەهێنێت کە تێیدا نووسراوە. بە جاری داهاتووی بەردەوام دەبێت:

break inside a nested loopbreak لەناو خولێکی ناوەکیداMATLABType in a terminalلە تێرمیناڵدا بینووسە
for i = 1:3
    for j = 1:3
        if j == 2
            break      % ends the j loop only
        end
        fprintf('i = %d, j = %d\n', i, j)
    end
end

break belongs inside a loop. Written outside any loop it is an error in a MATLAB file. To leave a function early you use return instead (leaving early with return).

break شوێنی لەناو . ئەگەر لە دەرەوەی هەموو بنووسرێت، لە MATLABـدا . بۆ زوو جێهێشتنی لە جیاتی ئەوە return بەکار دەهێنیت (زوو دەرچوون بە return).

continue: skipping the rest of one turncontinue: بازدان بە سەر باقیی یەک جاردا

The is the gentle cousin of break: it skips the rest of the current turn and goes straight to the next one; the loop itself goes on. Here −1 marks an absent student, and the absent ones are skipped:

ئامۆزای نەرمی breakـە: باقیی جاری ئێستا باز دەدات و ڕاستەوخۆ دەچێت بۆ جاری داهاتوو؛ خودی بەردەوام دەبێت. لێرەدا −1-1 نیشانەی قوتابیی ئامادەنەبووە و ئامادەنەبووەکان باز دەدرێن:

Skipping absent studentsبازدان بە سەر قوتابیی ئامادەنەبووداMATLABType in a terminalلە تێرمیناڵدا بینووسە
marks = [72 -1 88 95 -1 60];   % -1 = absent
total = 0;
count = 0;
for m = marks
    if m < 0
        continue                  % skip this turn
    end
    total = total + m;
    count = count + 1;
end
fprintf('%d marks, mean %.2f\n', count, total/count)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

For −1, lines 8 and 9 are skipped and the loop takes the next mark.

بۆ −1-1، دێڕەکانی 8 و 9 باز دەدرێن و نمرەی داهاتوو وەردەگرێت.

MATLAB can also do this job without a loop: mean(marks(marks >= 0)) keeps only the marks that pass the test (comparing a whole vector). Use continue when the body is long and you want to drop the unwanted cases early.

MATLAB دەتوانێت ئەم کارە بەبێ بکات: mean(marks(marks >= 0)) تەنها ئەو نمرانە دەهێڵێتەوە کە لە تاقیکردنەوەکە دەردەچن (بەراوردکردنی ئاڕاستەبڕێکی تەواو). continue بەکار بهێنە کاتێک جەستەکە درێژە و دەتەوێت حاڵەتە نەویستراوەکان زوو لاببەیت.

Quick checkپشکنینی خێراWhat is the difference between break and continue?جیاوازیی نێوان break و continue چییە؟

for or while?for یان while؟

Choosing the loopهەڵبژاردنی
The jobکارەکەLoopWhyبۆچی
Add the 10 marks of a classکۆکردنەوەی ⁦10⁩ نمرەی پۆلێکforthe number of turns is knownژمارەی جارەکان زانراوە
Do something with every element of a vectorکارێک لەگەڵ هەموو forfor x = v takes each element in turnfor x = v هەر بە نۆبە وەردەگرێت
Read numbers until a negative oneخوێندنەوەی ژمارە تا whilenobody knows how many will comeکەس نازانێت چەندیان دێت
Double until the amount passes 1000دوو هێندەکردن تا بڕەکە لە ⁦1000⁩ تێدەپەڕێتwhilethe answer is the number of turnsوەڵامەکە خودی ژمارەی جارەکانە
Halve an interval until it is small enoughنیوەکردنی تا بەس بچووک دەبێتwhilestops when an accuracy is reached (finding roots)کاتێک وردییەک بەدەست هات دەوەستێت (دۆزینەوەی ڕەگ)

A useful rule: if you can write the number of turns before the loop starts, use for — it changes its variable by itself, so it cannot become infinite by accident. If the loop must stop when something happens, use while and check its three parts.

یاسایەکی بەسوود: ئەگەر دەتوانیت ژمارەی جارەکان پێش دەستپێکردنی بنووسیت، for بەکار بهێنە — خۆی دەگۆڕێت، بۆیە بە هەڵە نابێتە . ئەگەر دەبێت کاتێک شتێک ڕوو دەدات بوەستێت، while بەکار بهێنە و سێ بەشەکەی بپشکنە.

Quick checkپشکنینی خێراA program must keep reading prices until the total passes 100,000 IQD. Which loop fits? دەبێت بەردەوام نرخ بخوێنێتەوە تا کۆکە لە ⁦100,000⁩ دینار تێدەپەڕێت. کام گونجاوە؟

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

While-loop mistakes and their fixesهەڵەکانی و چاککردنیان
MistakeهەڵەWhat happensچی ڕوو دەداتFixچاککردن
No change inside the loop (lab programs 2 and 4)هیچ گۆڕانێک لەناو نییە ( 2 و 4ـی تاقیگە)an infinite loop; Busy for ever؛ Busy بۆ هەمیشەadd the change, e.g. counter = counter + 1;; stop with Ctrl+Cگۆڕانەکە زیاد بکە، بۆ نموونە counter = counter + 1;؛ بە ⁦Ctrl+C⁩ بیوەستێنە
A change in the wrong direction (amount = amount/2 while waiting to pass 1000)گۆڕان بە ئاڕاستەی هەڵە (amount = amount/2 کاتێک چاوەڕێی تێپەڕینی ⁦1000⁩ دەکەیت)an infinite loopmake the change move towards a false conditionگۆڕانەکە بەرەو هەڵە ببە
A condition that is false at the start کە لە سەرەتادا هەڵەیەthe body runs zero times, silentlyجەستەکە سفر جار جێبەجێ دەبێت، بە بێدەنگیcheck the start values سەرەتا بپشکنە
Testing a decimal for exact equality: x = 0; while x ~= 1, x = x + 0.1; endتاقیکردنەوەی ژمارەی دەیی بۆ یەکسانیی ڕێک: x = 0; while x ~= 1, x = x + 0.1; endten steps of 0.1 give 0.9999999999999999, never exactly 1: infiniteدە هەنگاوی ⁦0.1⁩ دەبێتە ⁦0.9999999999999999⁩، هەرگیز ڕێک 1 نا: بێکۆتاuse < or a tolerance: while x < 1 - 1e-9 (round-off)< یان پەراوێزێک بەکار بهێنە: while x < 1 - 1e-9 (هەڵەی نزیککردنەوە)
Dividing by the planned count after breakدابەشکردن بە ژمارەی پلاندانراو دوای breaka wrong average (38.75 instead of 77.5) هەڵە (⁦38.75⁩ لە جیاتی ⁦77.5⁩)count what was really addedئەوە بژمێرە کە بەڕاستی کۆ کراوەتەوە
continue before the change in a while loopcontinue پێش گۆڕان لە whileـداthe change is skipped: infiniteگۆڕانەکە باز دەدرێت: بێکۆتاchange first, then continueیەکەم گۆڕان، پاشان continue
break outside a loopbreak لە دەرەوەی an erroruse return to leave a functionبۆ جێهێشتنی return بەکار بهێنە
Quick checkپشکنینی خێراx = 0; while x ~= 1, x = x + 0.1; end — what happens?x = 0; while x ~= 1, x = x + 0.1; end — چی ڕوو دەدات؟

Practiceڕاهێنان

Exerciseڕاهێنان1. How many digits?1. چەند تاکژمارە؟

Write a while loop that counts the digits of a positive whole number n. Test it with 70321. Hint: fix(n/10) drops the last digit.

بنووسە کە موجەبی n بژمێرێت. بە ⁦70321⁩ تاقیی بکەرەوە. ڕێنمایی: fix(n/10) دوایین لادەبات.

Hintئاماژە

Start value ndigits = 0; condition n > 0; change n = fix(n/10).

سەرەتا ndigits = 0؛ n > 0؛ گۆڕان n = fix(n/10).

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
n = 70321;
ndigits = 0;
while n > 0
    n = fix(n/10);
    ndigits = ndigits + 1;
end
ndigits
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The change: 70321 → 7032 → 703 → 70 → 7 → 0.

گۆڕانەکە: ⁦70321⁩ ← ⁦7032⁩ ← ⁦703⁩ ← ⁦70⁩ ← 7 ← 0.

Exerciseڕاهێنان2. A savings goal2. ئامانجێکی پاشەکەوت

Karwan puts 250,000 IQD in a savings account that adds 5 % every year. After how many years is the balance at least 400,000 IQD, and what is it then? Print both with fprintf.

کاروان ⁦250,000⁩ دینار لە هەژمارێکی پاشەکەوتدا دادەنێت کە ساڵانە ⁦5 %⁩ زیاد دەکات. دوای چەند ساڵ بڕی هەژمارەکە لانیکەم ⁦400,000⁩ دینار دەبێت و ئەو کاتە چەندە؟ هەردووکیان بە fprintf چاپ بکە.

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
balance = 250000;
years = 0;
while balance < 400000
    balance = 1.05*balance;
    years = years + 1;
end
fprintf('%d years, %.2f IQD\n', years, balance)
Exerciseڕاهێنان3. The largest power of 3 below 10003. گەورەترین توانی 3 لە خوار ⁦1000⁩

Start with p = 1 and multiply by 3 while the next power is still below 1000. What is p at the end?

بە p = 1 دەست پێبکە و مادام توانی داهاتوو هێشتا لە خوار ⁦1000⁩دایە، لێکی بدە لە 3. p لە کۆتاییدا چەندە؟

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
p = 1;
while 3*p < 1000
    p = 3*p;
end
p

729=36729 = 3^6; the next power, 37=21873^7 = 2187, is above 1000.

729=36729 = 3^6؛ توانی داهاتوو، 37=21873^7 = 2187، لە ⁦1000⁩ زیاترە.

Exerciseڕاهێنان4. Trace the endless loop4. بەدواداچوون بۆ خولە بێکۆتاکە بکە

Fill a trace table for the first three turns of the buggy lab program 2 with x = 1: the values of counter, J, pow and y at the end of each turn. What tells you the loop will never end?

بۆ سێ جاری یەکەمی 2ـی هەڵەداری تاقیگە بە ⁦x = 1⁩ پڕ بکەرەوە: counter، J، pow و y لە کۆتایی هەر جارێکدا. چی پێت دەڵێت هەرگیز کۆتایی نایەت؟

Show answerوەڵامەکە پیشان بدە
End of each turn (values from Python)کۆتایی هەر جارێک ( لە Pythonـەوە)
TurnجارcounterJpowy
11−130.2678
21150.2486
31−170.2500

The counter column never changes, so counter <= 10 can never become false.

ستوونی counter هەرگیز ناگۆڕێت، بۆیە counter <= 10 هەرگیز ناتوانێت هەڵە بێت.

Exerciseڕاهێنان5. Collatz steps5. هەنگاوەکانی کۆلاتز

Start with n = 6. While n is not 1: if n is even, halve it; otherwise replace it with 3n+13n+1. Count the steps and print the numbers you visit. (Nobody has proved that this loop ends for every start — a famous open question.)

بە ⁦n = 6⁩ دەست پێبکە. مادام n یەکسان نییە بە 1: ئەگەر n جووت بوو، نیوەی بکە؛ ئەگینا بیکە بە 3n+13n+1. هەنگاوەکان بژمێرە و ئەو ژمارانەی پێیاندا تێدەپەڕیت چاپ بکە. (کەس نەیسەلماندووە کە ئەم بۆ هەموو سەرەتایەک کۆتایی دێت — پرسیارێکی کراوەی بەناوبانگە.)

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
n = 6;
steps = 0;
fprintf('%d ', n)
while n ~= 1
    if mod(n, 2) == 0
        n = n/2;
    else
        n = 3*n + 1;
    end
    steps = steps + 1;
    fprintf('%d ', n)
end
fprintf('\n%d steps\n', steps)
Exerciseڕاهێنان6. A safer factorial loop6. خولێکی فاکتۆریێلی سەلامەتتر

Improve the tidy version of lab program 3: if the number is not whole (for example 2.5), print Whole numbers only and ask again instead of stopping with an error.

وەشانە ڕێکخراوەکەی 3ـی تاقیگە باشتر بکە: ئەگەر ژمارەکە تەواو نەبوو (بۆ نموونە ⁦2.5⁩)، Whole numbers only چاپ بکە و دووبارە بپرسە لە جیاتی ئەوەی بە بوەستێت.

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
x = input('Whole number (negative to stop): ');
while x >= 0
    if x == fix(x)
        fprintf('%d! = %d\n', x, factorial(x))
    else
        disp('Whole numbers only')
    end
    x = input('Whole number (negative to stop): ');
end
disp('Goodbye')

Summaryپوختە

  • while condition … end repeats while the condition is true; it is tested before every turn, so the body may run zero times.
  • Every while loop needs a start value, a condition and a change that moves the condition towards false.
  • No change (lab programs 2 and 4) means an : press Ctrl+C in the Command Window.
  • A such as a negative number ends input loops; while true … if … break … end asks again until the input is valid.
  • break ends the innermost loop at once — afterwards, divide by what was really counted. continue skips only the rest of the current turn.
  • Known number of turns → for; until something happens → while. Huge factorials are stored as rounded doubles.
  • while condition … end مادام ڕاست بێت دووبارە دەکاتەوە؛ پێش هەموو جارێک تاقی دەکرێتەوە، بۆیە لەوانەیە جەستەکە سفر جار جێبەجێ ببێت.
  • هەموو پێویستی بە سەرەتا، و گۆڕانێک هەیە کە بەرەو هەڵە ببات.
  • نەبوونی گۆڕان ( 2 و 4ـی تاقیگە) واتە : لە ⁦Command Window⁩ ⁦Ctrl+C⁩ دابگرە.
  • وەک کۆتایی پێ دەهێنێت؛ while true … if … break … end دووبارە دەپرسێت تا دروست دەبێت.
  • break یەکسەر ناوەکیترین کۆتایی پێ دەهێنێت — دوای ئەوە بەوە دابەش بکە کە بەڕاستی ژمێردراوە. continue تەنها باقیی جاری ئێستا باز دەدات.
  • ژمارەی زانراوی جار ← for؛ تا شتێک ڕوو دەدات ← while. وەک doubleـی نزیککراوە هەڵدەگیرێن.

If you know Python: its while loop works the same way, including endless loops stopped with Ctrl+C and break/continue — see infinite loops in Python and break.

ئەگەر Python دەزانیت: لەوێدا بە هەمان شێوە کار دەکات، بە کە بە ⁦Ctrl+C⁩ دەوەستێنرێن و break/continue — بڕوانە خولە بێکۆتاکان لە Pythonـدا و break.

Review questionsپرسیارەکانی پێداچوونەوە
A while loop prints nothing and MATLAB says Busy. What is the most likely cause?خولێکی while هیچ چاپ ناکات و MATLAB دەڵێت Busy. ئەگەری زۆری هۆکار چییە؟

Nothing in the body changes the variables of the condition, so it stays true. Press Ctrl+C, then add or fix the change.

هیچ شتێک لە جەستەکەدا ناگۆڕێت، بۆیە ڕاست دەمێنێتەوە. ⁦Ctrl+C⁩ دابگرە، پاشان گۆڕانەکە زیاد بکە یان چاکی بکە.

Why is while true not always a bug?بۆچی while true هەمیشە باگ نییە؟

Because a break inside the loop can end it at the right moment — the usual way to ask again until the input is valid.

چونکە breakـێک لەناو دەتوانێت لە کاتی گونجاودا کۆتایی پێ بهێنێت — ڕێگای باوی دووبارە پرسین تا دروست دەبێت.

What does break do inside two nested loops?break لەناو خولێکی ناوەکیدا چی دەکات؟

It ends only the inner loop; the outer loop continues with its next turn.

تەنها کۆتایی پێ دەهێنێت؛ بە جاری داهاتووی بەردەوام دەبێت.

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

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

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

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

Function Files and Anonymous Functionsفایلەکانی کردار و کردارە بێناوەکان

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

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