JavaJava · Chapterبەش 7 · Lectureوانە 7.1

The while and do-while Loopsخولی while و خولی ⁦do...while⁩

Why programs repeat work and Java's three loops; the while loop with its condition, body and update; a counter-controlled loop, counting down, an accumulator that adds 1 to 20 (210, checked with n(n+1)2\frac{n(n+1)}{2}) and even numbers two ways; infinite loops, Ctrl+C and a semicolon after while; the do-while loop that runs at least once, a sentinel loop that reads until 0, the largest-number exercise, and pretest against posttest loops.

بۆچی کار دووپاتە دەکەنەوە و سێ Java؛ لەگەڵ ، و نوێکردنەوە؛ ، ژماردنی پێچەوانە، کە 1 تا ⁦20⁩ کۆ دەکاتەوە (⁦210⁩، بە n(n+1)2\frac{n(n+1)}{2} پشکنراوە) و ژمارە جووتەکان بە دوو ڕێگا؛ ، ⁦Ctrl+C⁩ و لە دوای while؛ کە لانیکەم یەک جار جێبەجێ دەبێت، پاسەوان کە تا 0 دەخوێنێتەوە، ڕاهێنانی گەورەترین ژمارە و بەرامبەر .

16 min read16 خولەک خوێندنەوە · 18 stepsهەنگاو

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

  • Write a while loop with a start value, a condition and an update, and say how many times its body runs.
  • Use counters, accumulators and sentinel values, and find and stop infinite loops.
  • Write a do-while loop, explain why it runs at least once, and end it with ;.
  • Tell a pretest loop from a posttest loop and choose between while and do-while.
  • بە سەرەتا، و نوێکردنەوە بنووسیت و بڵێیت جەستەکەی چەند جار جێبەجێ دەبێت.
  • ، و بەکار بهێنیت و بدۆزیتەوە و ڕایانبگریت.
  • بنووسیت، ڕوونی بکەیتەوە بۆچی لانیکەم یەک جار جێبەجێ دەبێت و بە ; کۆتایی پێ بهێنیت.
  • لە جیا بکەیتەوە و لە نێوان while و ⁦do-while⁩ـدا هەڵبژێریت.

Why loops?بۆچی خول؟

A tells a program to run the same statements again and again. To print Welcome to Java! ten times you do not copy the line ten times: you write it once inside a loop, and for a thousand times you change only one number. One pass through the loop is one , and the loop goes on as long as a condition stays true.

بە دەڵێت هەمان دووپاتە و دووپاتە جێبەجێ بکات. بۆ ئەوەی Welcome to Java! دە جار چاپ بکەیت، دێڕەکە دە جار کۆپی ناکەیت: یەک جار لە ناو دەینووسیت و بۆ هەزار جاریش تەنیا ژمارەیەک دەگۆڕیت. هەر جارێک تێپەڕبوون بە ناو و بەردەوام دەبێت تا ڕاست بمێنێتەوە.

A running track seen from above, with arrows going round it and a runner on the track. A lap counter shows 3 / 10. Three labels: one lap = one iteration; lap counter = the variable count; go on while count < 10.ڕێڕەوێکی ڕاکردن لە سەرەوە، تیرەکان بە دەوریدا دەسوڕێنەوە و ڕاکەرێک لەسەریەتی. ژمێرەری سووڕەکان 3 / 10 پیشان دەدات. سێ نووسین: یەک سووڕ = یەک خولانەوە؛ ژمێرەری سووڕەکان = گۆڕاوەکە count؛ تا count < 10 بێت، بەردەوام بە.
Lap after lap: each lap is one iterationسووڕ لە دوای سووڕ: هەر سووڕێک یەک CêIT

Java has three loops. They do the same basic job but are written differently and test their condition at different moments: while and do … while in this lesson, for in The for loop. A fourth form, the , walks through arrays and lists (a first look). Repetition is one of the three building blocks of every algorithm (Three building blocks).

Java سێ هەیە. هەمان کاری بنەڕەتی دەکەن، بەڵام جیاواز دەنووسرێن و لە کاتی جیاوازدا دەپشکنن: while و do … while لەم وانەیەدا، for لە خولی for. شێوەی چوارەم، ، بە ناو و لیستەکاندا دەڕوات (یەکەم سەیرکردن). دووپاتەکردنەوە یەکێکە لە سێ بەردی بناغەی هەموو (سێ بەردی بناغە).

The while loopخولی while

Definitionپێناسە

A loop that checks its condition first and repeats its block as long as the condition is true. If the condition is false at the start, the block never runs.

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

A while loop repeats its body while its condition is true. Java tests the condition before every round: true means run the body once more; false means jump past the loop to the next statement.

دووپاتە دەکاتەوە تا ڕاست بێت. Java پێش هەموو دەپشکنێت: ڕاست واتە جارێکی تر جێبەجێ بکە؛ هەڵە واتە بە سەر باز بدە بۆ دواتر.

The shape of a while loopشێوەی خولی whileTEXT
while (loop-continuation-condition) {
    // loop body
    statement(s);
}
The loop int count = 0; while (count < 10) { System.out.println("Welcome to Java!"); count++; } with its parts labelled: the start value before the loop, the condition tested before every round, the body that runs while the condition is true, the update that brings count closer to the end, and the closing brace after which the program goes on when the condition is false.خولەکە int count = 0; while (count < 10) { System.out.println("Welcome to Java!"); count++; } بە ناوی بەشەکانییەوە: نرخی سەرەتا پێش خولەکە، مەرجەکە کە پێش هەموو خولانەوەیەک دەپشکنرێت، جەستەی خولەکە کە تا مەرجەکە ڕاست بێت جێبەجێ دەبێت، نوێکردنەوە کە count لە کۆتایی نزیک دەکاتەوە و کەوانەی داخستن کە بەرنامەکە لە دوای ئەو بەردەوام دەبێت کاتێک مەرجەکە هەڵە بوو.
Start value, condition, body and update سەرەتا، ، و نوێکردنەوەCêIT
  • The is a boolean expression in brackets: true or false (Booleans).
  • The is the block in braces { }.
  • Something in the body must change the condition, or the loop never ends (Infinite loops).
  • لە ناو کەوانەدا: true یان false (بوولیانەکان).
  • ئەو کە لە ناو { }ـدایە.
  • شتێک لە ناو دەبێت بگۆڕێت، ئەگینا هەرگیز کۆتایی نایەت (خولە بێکۆتاکان).

Why is it called “while”?بۆچی پێی دەوترێت «while»؟

In English, while means as long as: “while it is raining, stay inside”. A while loop reads the same way. while (x < 100) means “as long as x is less than 100, keep doing this”. The condition is checked before every round, and when it becomes false the loop stops.

لە ئینگلیزیدا while واتە «تا ئەو کاتەی»: «تا ئەو کاتەی باران دەبارێت، لە ماڵەوە بمێنەوە». بە هەمان شێوە دەخوێنرێتەوە. while (x < 100) واتە «تا ئەو کاتەی x لە ⁦100⁩ بچووکترە، ئەمە دووپاتە بکەرەوە». پێش هەموو دەپشکنرێت و کاتێک بوو بە false، دەوەستێت.

The word entered programming with ALGOL 60 (1960), where while was part of the for statement. ALGOL W, designed by Niklaus Wirth and Tony Hoare in 1966, made while a loop of its own, and Wirth kept it in Pascal (1970). C, Java, PHP, Python and MATLAB use the same word today. The whole story of the word is in the Honame section of the while loop term page.

وشەکە لەگەڵ ⁦ALGOL 60⁩ ⁦(1960)⁩ هاتە ناو بەرنامەسازییەوە، کە تێیدا while بەشێک بوو لە for. ALGOL W، کە نیکلاوس ڤیرت (Niklaus Wirth) و تۆنی هۆر (Tony Hoare) لە ساڵی ⁦1966⁩دا دیزاینیان کرد، whileـی کرد بە سەربەخۆ و ڤیرت لە Pascalـدا ⁦(1970)⁩ هێشتییەوە. ئەمڕۆ C، Java، PHP، Python و MATLAB هەمان وشە بەکاردەهێنن. هەموو چیرۆکی وشەکە لە بەشی «هۆنامە»ی پەڕەی زاراوەی خولی whileدایە.

do...while reads “do this, while the condition holds”: the body runs first and the check comes after it, so the body always runs at least once.

⁦do...while⁩ بەم شێوەیە دەخوێنرێتەوە: «ئەمە بکە، تا ئەو کاتەی ڕاستە»: سەرەتا لەشی جێبەجێ دەبێت و پشکنین دوای ئەو دێت، بۆیە لەشەکە هەمیشە لانیکەم یەک جار جێبەجێ دەبێت.

Ten times: a counter-controlled loopدە جار: خولی کۆنترۆڵکراو بە ژمێرەر

This loop prints Welcome to Java! ten times. The variable count counts the rounds: it is declared and set to 0 before the loop and increased by one inside it (count++, see Increment and decrement). You know in advance how many times the body runs, so this is a , and count is its control variable.

ئەم دە جار Welcome to Java! چاپ دەکات. count دەژمێرێت: پێش دەناسێنرێت و دەکرێتە 0 و لە ناو ئەودا یەکێکی بۆ زیاد دەکرێت (count++، بڕوانە زیادکردن و کەمکردنەوە). پێشتر دەزانیت چەند جار جێبەجێ دەبێت، بۆیە ئەمە و count .

WelcomeLoop.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class WelcomeLoop {
    public static void main(String[] args) {
        int count = 0;
        while (count < 10) {
            System.out.println("Welcome to Java!");
            count++;
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

The counter starts at 0, before the loop.

پێش لە 0ـەوە دەست پێ دەکات.

Lineدێڕی 4

Tested before every round: 10 times true, then false.

پێش هەموو دەپشکنرێت: ⁦10⁩ جار true، پاشان false.

Lineدێڕی 6

The update: without it the loop would never end.

نوێکردنەوەکە: بەبێ ئەو هەرگیز کۆتایی نایەت.

An animated flowchart: int count = 0, then the test count < 10, the body that prints Welcome to Java! and runs count++, and an arrow back to the test. A count box steps 0, 1, 2 … 10 while the terminal fills with lines. At 10 < 10 the test is false and the path leaves the loop: 10 rounds, 11 tests.
An animated flowchart: int count = 0, then the test count < 10, the body that prints Welcome to Java! and runs count++, and an arrow back to the test. A count box steps 0, 1, 2 … 10 while the terminal fills with lines. At 10 < 10 the test is false and the path leaves the loop: 10 rounds, 11 tests.
count steps from 0 to 10; the 11th test ends the loopcount لە 0ـەوە تا ⁦10⁩ هەنگاو دەنێت؛ پشکنینی یازدەیەم کۆتایی پێ دەهێنێتCêIT

Counting downژماردنی پێچەوانە

A loop can count down too. num starts at 6, the condition is num >= 0 and num-- takes one away in every round (decrement). The body runs 7 times, for 6, 5, 4, 3, 2, 1 and 0. Then num is −1, the test is false and the loop ends.

دەتوانێت بە پێچەوانەش بژمێرێت. num لە 6ـەوە دەست پێ دەکات، num >= 0ـە و num-- لە هەموو یەکێک کەم دەکاتەوە (کەمکردنەوە). 7 جار جێبەجێ دەبێت، بۆ 6، 5، 4، 3، 2، 1 و 0. پاشان num دەبێتە ⁦−1⁩، پشکنینەکە هەڵەیە و کۆتایی دێت.

Countdown.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Countdown {
    public static void main(String[] args) {
        int num = 6;
        while (num >= 0) {
            System.out.println("The value of num = " + num);
            num--;
        }
    }
}
Boxes going down like stairs: 6, 5, 4, 3, 2, 1, 0, each marked true, joined by arrows labelled num--. A last box, -1, is marked false. Text: 7 rounds print 6 to 0; then num is -1 and num >= 0 is false; the condition is tested 8 times.سندووقەکان وەک پلیکانە دادەبەزن: 6، 5، 4، 3، 2، 1، 0، هەریەکە بە نیشانەی true و بە تیری num-- بەیەکەوە بەستراون. دوا سندووق، -1، نیشانەی false دراوە. نووسین: 7 خولانەوە ژمارەکانی 6 تا 0 چاپ دەکەن؛ پاشان num دەبێتە -1 و num >= 0 هەڵەیە؛ مەرجەکە 8 جار دەپشکنرێت.
num-- after every line: seven lines, eight testsnum-- لە دوای هەموو دێڕێک: حەوت دێڕ، هەشت پشکنینCêIT

Adding 1 to 20: an accumulatorکۆکردنەوەی 1 تا ⁦20⁩: گۆڕاوی کۆکردنەوە

To add numbers in a loop, keep a running total in a variable that starts at 0 before the loop: an . Every round adds the current number: sum = sum + num (short form sum += num, compound assignment). This program adds 1 + 2 + … + 20:

بۆ کۆکردنەوەی ژمارەکان لە ، کۆی گشتی لە هەڵبگرە کە پێش لە 0ـەوە دەست پێ دەکات: . هەموو ژمارەی ئێستا زیاد دەکات: sum = sum + num (بە کورتی sum += num، کارپێکەرەکانی دانانی نرخ). ئەم ⁦1 + 2 + … + 20⁩ کۆ دەکاتەوە:

SumOneToTwenty.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SumOneToTwenty {
    public static void main(String[] args) {
        int num = 1;
        int sum = 0;
        while (num <= 20) {
            sum = sum + num;
            num++;
        }
        System.out.println("Sum from 1 to 20 = " + sum);
    }
}
A chain of sum boxes: 0, then +1 gives 1, +2 gives 3, +3 gives 6, +4 gives 10, +5 gives 15, … then 171, +19 gives 190 and +20 gives 210, after which the loop ends. Below: check with the formula 20 × 21 ÷ 2 = 210.زنجیرەیەک سندووقی sum: 0، پاشان +1 دەبێتە 1، +2 دەبێتە 3، +3 دەبێتە 6، +4 دەبێتە 10، +5 دەبێتە 15، … پاشان 171، +19 دەبێتە 190 و +20 دەبێتە 210، دوای ئەوە خولەکە کۆتایی دێت. لە خوارەوە: پشکنین بە فۆرمولەکە 20 × 21 ÷ 2 = 210.
The accumulator sum after every round sum لە دوای هەموو CêIT
1+2+⋯+n=n(n+1)220⋅212=2101 + 2 + \cdots + n = \frac{n(n+1)}{2} \qquad \frac{20 \cdot 21}{2} = 210

The formula for the sum of the first n whole numbers gives the same 210, so the loop is right.

کۆی یەکەم n ژمارە هەمان ⁦210⁩ دەدات، بۆیە دروستە.

Adding 1 to 20: an accumulatorکۆکردنەوەی 1 تا ⁦20⁩: گۆڕاوی کۆکردنەوە

Follow the sum by handsum بە دەست بەدوادا بچۆ

A shows every step: one column per variable, one row per round. Here is the same loop with 4 instead of 20; a real run that prints both variables in each round gives num = 1, sum = 1 up to After the loop: num = 5, sum = 10. The method is taught in Tracing a loop with a trace table and Checking with a trace table, and the trace lab traces Java loops step by step.

هەموو هەنگاوێک نیشان دەدات: بۆ هەر ستوونێک و بۆ هەر ڕیزێک. ئەمە هەمان بە 4 لە جیاتی ⁦20⁩؛ جێبەجێکردنێکی ڕاستەقینە کە لە هەر هەردوو چاپ دەکات، لە num = 1, sum = 1ـەوە تا After the loop: num = 5, sum = 10 دەدات. ڕێگاکە لە خشتەی بەدواداچوون: خولێک بە دەست جێبەجێ بکە و پشکنین بە خشتەی بەدواداچوون فێر دەکرێت و تاقیگەی بەدواداچوون Java هەنگاو بە هەنگاو بەدوادا دەچێت.

The sum loop with 4 instead of 20 sum بە 4 لە جیاتی ⁦20⁩
Test numberژمارەی پشکنینnum at the testnum لە کاتی پشکنینnum <= 4sum after the bodysum دوای
11true1
22true3
33true6
44true10
55false10 (the loop ends)⁦10⁩ ( کۆتایی دێت)

Even numbers, two waysژمارە جووتەکان، بە دوو ڕێگا

This loop prints the even numbers from 1 to 20. It visits every number and prints only those that leave no remainder when divided by 2: i % 2 == 0 (remainder).

ئەم ژمارە جووتەکان لە 1 تا ⁦20⁩ چاپ دەکات. سەردانی هەموو ژمارەیەک دەکات و تەنیا ئەوانە چاپ دەکات کە کاتێک دابەشی 2 دەکرێن هیچ نامێنێتەوە: i % 2 == 0 (پاشماوە).

EvenNumbers.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class EvenNumbers {
    public static void main(String[] args) {
        int i = 1;
        System.out.println("Even numbers from 1 to 20:");
        while (i <= 20) {
            if (i % 2 == 0) {
                System.out.print(i + " ");
            }
            i++;
        }
        System.out.println();
    }
}

With println instead of print, each number would stand on its own line. Simpler still: start at 2 and jump by 2. No if is needed, and the loop makes 10 rounds instead of 20:

ئەگەر لە جیاتی print نووسرابا println، هەر ژمارەیەک لە دێڕی خۆیدا دەبوو. ڕێگایەکی سادەتر: لە 2ـەوە دەست پێ بکە و دوو دوو باز بدە. پێویست بە if ناکات و لە جیاتی ⁦20⁩، ⁦10⁩ دەکات:

EvenStep.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class EvenStep {
    public static void main(String[] args) {
        int i = 2;
        System.out.println("Even numbers from 1 to 20:");
        while (i <= 20) {
            System.out.print(i + " ");
            i += 2;
        }
        System.out.println();
    }
}
Two rows of the numbers 1 to 20. Top row: every number is visited with i++ and the ten even numbers are coloured as printed: 20 rounds, 10 numbers printed. Bottom row: the loop starts at 2 and jumps with i += 2, visiting only 2, 4, … 20: 10 rounds and no if.دوو ڕیزی ژمارەکانی 1 تا 20. ڕیزی سەرەوە: بە i++ سەردانی هەموو ژمارەیەک دەکرێت و دە ژمارە جووتەکە وەک چاپکراو ڕەنگ کراون: 20 خولانەوە، 10 ژمارە چاپ دەکرێن. ڕیزی خوارەوە: خولەکە لە 2ـەوە دەست پێ دەکات و بە i += 2 باز دەدات و تەنیا سەردانی 2، 4، … 20 دەکات: 10 خولانەوە و بێ if.
Visit everything and filter, or jump straight to the answersسەردانی هەموو بکە و هەڵبژێرە، یان ڕاستەوخۆ باز بدە بۆ وەڵامەکانCêIT

Infinite loops and Ctrl+Cخولە بێکۆتاکان و ⁦Ctrl+C⁩

If nothing in the body changes the condition, it stays true for ever: an . Forget count++ and count stays 0, so count < 10 is never false. The program prints the same line again and again until you stop it:

ئەگەر هیچ شتێک لە ناو نەگۆڕێت، بۆ هەمیشە ڕاست دەمێنێتەوە: . count++ لەبیر بکە و count هەر 0 دەمێنێتەوە، بۆیە count < 10 هەرگیز هەڵە نابێت. هەمان دێڕ دووپاتە و دووپاتە چاپ دەکات تا ڕای دەگریت:

Forgot.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Forgot {
    public static void main(String[] args) {
        int count = 0;
        while (count < 10) {
            System.out.println("count is " + count);
        }
    }
}
The loop int count = 0; while (count < 10) { System.out.println("count is " + count); } with an empty dashed box where count++; is missing. A circular arrow repeats count is 0 for ever, and the keys Ctrl + C stop the program in a terminal. Fix: put count++; at the end of the body.خولەکە int count = 0; while (count < 10) { System.out.println("count is " + count); } لەگەڵ سندووقێکی پچڕپچڕی بەتاڵ لە شوێنی count++;ـی ون. تیرێکی بازنەیی count is 0 بۆ هەمیشە دووپاتە دەکاتەوە و دوگمەکان Ctrl + C بەرنامەکە لە تێرمیناڵدا ڕادەگرن. چارەسەر: count++; بخەرە کۆتایی جەستەی خولەکە.
Without an update the condition never changesبەبێ نوێکردنەوە هەرگیز ناگۆڕێتCêIT

Infinite loops and Ctrl+Cخولە بێکۆتاکان و ⁦Ctrl+C⁩

A semicolon after while (…)خاڵبۆر لە دوای ⁦while (…)⁩

A ; straight after while (…) is a complete statement that does nothing (an empty statement), and it becomes the whole loop body. The block below it is no longer part of the loop. Here i stays 0, so while (i < 3); runs for ever and prints nothing, not even Done:

;ـێک ڕاستەوخۆ لە دوای while (…) تەواوە کە هیچ ناکات ( بەتاڵ) و دەبێتە هەموو . بلۆکەکەی ژێرەوەی ئیتر بەشێک نییە لە . لێرەدا i هەر 0 دەمێنێتەوە، بۆیە while (i < 3); بۆ هەمیشە کار دەکات و هیچ چاپ ناکات، تەنانەت Doneـیش نا:

EmptyWhile.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class EmptyWhile {
    public static void main(String[] args) {
        int i = 0;
        while (i < 3); {
            System.out.println(i);
            i++;
        }
        System.out.println("Done");
    }
}
The program with while (i < 3); on line 2, the semicolon highlighted as the whole loop body, an empty statement, with a small circular arrow: i stays 0, so the loop runs for ever doing nothing. The block below and the last println are dimmed: never reached, nothing is printed, not even Done. javac -Xlint:all gives no warning.بەرنامەکە لەگەڵ while (i < 3); لە دێڕی 2، خاڵبۆرەکە وەک هەموو جەستەی خولەکە ڕەنگ کراوە، ڕستەیەکی بەتاڵ، لەگەڵ تیرێکی بازنەیی بچووک: i هەر 0 دەمێنێتەوە، بۆیە خولەکە بۆ هەمیشە کار دەکات و هیچ ناکات. بلۆکەکەی ژێرەوە و دوا println کاڵ کراونەتەوە: هەرگیز ناگاتە ئەوێ و هیچ چاپ ناکرێت، تەنانەت Doneـیش نا. javac -Xlint:all هیچ هۆشدارییەک نادات.
The ; is the loop body; the block below never runs;ـەکە ؛ بلۆکەکەی ژێرەوە هەرگیز جێبەجێ نابێتCêIT

javac warns about an empty statement only after if, not after while, even with -Xlint:all (A semicolon after if). Never put ; after while (…) when a block follows; the one ; that belongs to a loop header ends a do-while loop (next screen).

javac تەنیا لە دوای if ئاگادارت دەکاتەوە لە بەتاڵ، نەک لە دوای while، تەنانەت بە -Xlint:all (خاڵبۆر لە دوای if). هەرگیز لە دوای while (…) ; مەنووسە کاتێک بلۆکێک بەدوایدا دێت؛ تاکە ;ـێک کە سەر بە کۆتایی (شاشەی دواتر).

The do-while loopخولی ⁦do...while⁩

A is a while loop turned upside down: it runs the body first and tests the condition afterwards. If the test is true, the body runs again; if it is false, the loop ends.

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

The shape of a do-while loopشێوەی خولی ⁦do...while⁩TEXT
do {
    // loop body
    statement(s);
} while (loop-continuation-condition);
DoWhileCount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class DoWhileCount {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}
Left: the program int i = 1; do { System.out.println(i); i++; } while (i <= 10); with the semicolon at the end marked: this ; ends the do-while statement; without it javac says ';' expected. Right: a flowchart: i = 1, then the body println(i); i++;, then the test i <= 10; true goes back up to the body, false leaves the loop.لای چەپ: بەرنامەکە int i = 1; do { System.out.println(i); i++; } while (i <= 10); و خاڵبۆرەکە کۆتایی نیشان کراوە: ئەم ;ـە ڕستەکەی do-while تەواو دەکات؛ بەبێ ئەو javac دەڵێت ';' expected. لای ڕاست: هێڵکاریی ڕەوت: i = 1، پاشان جەستەی خولەکە println(i); i++;، پاشان پشکنینی i <= 10؛ true دەگەڕێتەوە سەرەوە بۆ جەستەی خولەکە و false لە خولەکە دەردەچێت.
The body comes first; the test decides whether it runs again یەکەمە؛ پشکنینەکە بڕیار دەدات دیسان جێبەجێ بێت یان ناCêIT

Mind the ; after while (i <= 10): it ends the do-while statement, and without it javac stops with ';' expected. A plain while loop must not have one there.

ئاگاداری ;ـەکەی دوای while (i <= 10) بە: ⁦do-while⁩ تەواو دەکات و بەبێ ئەو javac بە ';' expected دەوەستێت. ئاسایی نابێت لەو شوێنەدا هیچ ;ـێکی هەبێت.

At least onceلانیکەم یەک جار

The difference shows when the condition is false from the start. With the start value 100, while (i <= 10) tests first and never runs its body. The do-while loop runs its body once and only then finds that 101 <= 10 is false:

جیاوازییەکە کاتێک دەردەکەوێت کە لە سەرەتاوە هەڵە بێت. بە سەرەتای ⁦100⁩، while (i <= 10) سەرەتا دەپشکنێت و هەرگیز جێبەجێ ناکات. یەک جار جێبەجێ دەکات و تەنیا پاشان دەبینێت کە 101 <= 10 هەڵەیە:

AtLeastOnce.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class AtLeastOnce {
    public static void main(String[] args) {
        int i = 100;
        while (i <= 10) {
            System.out.println("while: " + i);
            i++;
        }
        int j = 100;
        do {
            System.out.println("do-while: " + j);
            j++;
        } while (j <= 10);
        System.out.println("Finished: i = " + i + ", j = " + j);
    }
}
Two code panels side by side, both starting with the value 100. The while loop tests 100 <= 10 first: false, so its body is skipped and its terminal stays empty. The do-while loop runs its body first and prints do-while: 100, then tests 101 <= 10: false, and stops. Result: body 0 times against body 1 time.
Two code panels side by side, both starting with the value 100. The while loop tests 100 <= 10 first: false, so its body is skipped and its terminal stays empty. The do-while loop runs its body first and prints do-while: 100, then tests 101 <= 10: false, and stops. Result: body 0 times against body 1 time.
A do-while body always runs at least onceلە ⁦do-while⁩ـدا هەمیشە لانیکەم یەک جار جێبەجێ دەبێتCêIT

Python has no do-while loop; it imitates one with while True and break (do … while: Java only).

Python نییە؛ بە while True و break لاسایی دەکاتەوە (⁦do … while⁩: تەنیا لە Javaـدا).

Read until 0: a sentinel valueتا 0 بخوێنەوە: نرخی پاسەوان

Often nobody knows in advance how many numbers will be typed. Then a special value means stop: a . This program adds integers until the input is 0. A do-while fits, because a number must be read before it can be tested (Scanner setup):

زۆرجار کەس پێشتر نازانێت چەند ژمارە دەنووسرێت. ئەوکات تایبەت واتای بوەستە دەدات: . ئەم کۆ دەکاتەوە تا دەبێتە 0. گونجاوە، چونکە دەبێت ژمارەیەک بخوێندرێتەوە پێش ئەوەی بپشکنرێت (ئامادەکردنی Scanner):

TestDoWhile.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class TestDoWhile {
    public static void main(String[] args) {
        int data;
        int sum = 0;
        Scanner input = new Scanner(System.in);
        do {
            System.out.print("Enter an integer (the input ends if it is 0): ");
            data = input.nextInt();
            sum += data;
        } while (data != 0);
        System.out.println("The sum is " + sum);
    }
}
Number boxes 3, 5, 6 and 0 on a conveyor belt moving into a machine that does sum += data and shows sum = 14. The 0 box has a stop sign: 0 = stop. Text: 3 + 5 + 6 + 0 = 14; the 0 is added too, changes nothing and ends the loop; a sentinel must be a value that can never be real data.سندووقی ژمارەکانی 3، 5، 6 و 0 لەسەر پشتێنەیەکی گوازەرەوە دەچنە ناو ئامێرێک کە sum += data دەکات و sum = 14 پیشان دەدات. سندووقی 0 نیشانەی وەستانی پێوەیە: 0 = بوەستە. نووسین: 3 + 5 + 6 + 0 = 14؛ سفریش کۆ دەکرێتەوە، هیچ ناگۆڕێت و خولەکە کۆتایی پێ دەهێنێت؛ نرخی پاسەوان دەبێت نرخێک بێت کە هەرگیز دراوەیەکی ڕاستەقینە نەبێت.
The numbers arrive one by one; 0 means the endژمارەکان یەک بە یەک دێن؛ 0 واتە کۆتاییCêIT

The 0 is added too, which is harmless: adding 0 changes nothing. A sentinel must be a value that can never be real data. To test without typing, pipe the numbers in (Testing with a pipe); the prompts then run together on one line:

سفریش کۆ دەکرێتەوە و زیانی نییە: کۆکردنەوەی 0 هیچ ناگۆڕێت. دەبێت بێت کە هەرگیز ڕاستەقینە نەبێت. بۆ تاقیکردنەوە بەبێ نووسین، ژمارەکان بە pipe بنێرە ناو (تاقیکردنەوە بە pipe)؛ ئەوکات لە یەک دێڕدا بەدوای یەکدا دێن:

BASHType in a terminalلە تێرمیناڵدا بینووسە
printf '3\n5\n6\n0\n' | java TestDoWhile

Exercise: the largest numberڕاهێنان: گەورەترین ژمارە

ExerciseڕاهێنانWhat is the output?دەرخستەکە چییە؟

Suppose the input is 2 3 4 5 0. What does this program print? Trace number and max before you look at the answer.

وا دابنێ 2 3 4 5 0ـە. ئەم چی چاپ دەکات؟ پێش سەیرکردنی وەڵامەکە بە دوای number و maxـدا بچۆ.

MaxUntilZero.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class MaxUntilZero {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number, max;
        number = input.nextInt();
        max = number;
        do {
            number = input.nextInt();
            if (number > max) {
                max = number;
            }
        } while (number != 0);
        System.out.println("max is " + max);
        System.out.println("number " + number);
    }
}
Hintئاماژە

number is read before the loop; the loop reads the rest.

number پێش دەخوێندرێتەوە؛ ئەوانی تر دەخوێنێتەوە.

Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
$ java MaxUntilZero
2 3 4 5 0
max is 5
number 0
Readخوێندراوەnumbernumber > maxmaxnumber != 0
before the loopپێش 2—2—
round 1 13true3true
round 2 24true4true
round 3 35true5true
round 4 40false5false

The first number, 2, is read before the loop and becomes max. The loop reads 3, 4, 5 and 0, and max grows to 5. The 0 ends the loop, but it is compared first; it is not larger than 5. All five numbers can be typed on one line because Scanner reads token by token (Tokens).

یەکەم ژمارە، 2، پێش دەخوێندرێتەوە و دەبێتە max. 3، 4، 5 و 0 دەخوێنێتەوە و max گەورە دەبێت تا ⁦5. 0⁩ کۆتایی پێ دەهێنێت، بەڵام سەرەتا بەراورد دەکرێت؛ لە 5 گەورەتر نییە. هەر پێنج ژمارەکە دەتوانرێت لە یەک دێڕدا بنووسرێن، چونکە Scanner پارچە بە پارچە دەخوێنێتەوە (پارچەکان).

Test first or test lastپشکنین لە سەرەتا یان لە کۆتایی

while tests its condition before the body: it is a . do … while tests after the body: it is a . A pretest loop may run its body zero times; a posttest loop always runs it at least once. Choose do-while when the body must run before the test makes sense, such as reading a number or showing a menu, and while otherwise. for is a pretest loop too (Which loop?).

while پێش دەپشکنێت: ـە. do … while دوای دەپشکنێت: ـە. لەوانەیە سفر جار جێبەجێ بکات؛ هەمیشە لانیکەم یەک جار جێبەجێی دەکات. کاتێک دەبێت پێش ئەوەی پشکنین واتای هەبێت جێبەجێ بێت، وەک خوێندنەوەی ژمارەیەک یان پیشاندانی ، ⁦do-while⁩ هەڵبژێرە؛ ئەگینا while. forـیش (کام خول؟).

Two flowcharts. Left, while and for, a pretest loop: the condition diamond comes first; true leads to the loop body and back to the test, false leaves the loop: the body runs 0 or more times. Right, do … while, a posttest loop: the body comes first, then the condition; true goes back to the body, false leaves: the body runs 1 or more times.دوو هێڵکاریی ڕەوت. چەپ، خولی while و خولی for، خولی پێشپشکنین: شێوەی ئەڵماسیی مەرج یەکەمە؛ true دەچێت بۆ جەستەی خول و دەگەڕێتەوە بۆ پشکنین، false لە خولەکە دەردەچێت: جەستەی خولەکە 0 جار یان زیاتر جێبەجێ دەبێت. ڕاست، خولی do...while، خولی پاشپشکنین: جەستەی خول یەکەمە، پاشان مەرج؛ true دەگەڕێتەوە بۆ جەستەی خول و false دەردەچێت: جەستەی خولەکە 1 جار یان زیاتر جێبەجێ دەبێت.
Pretest: zero or more times. Posttest: one or more times.: سفر جار یان زیاتر. : یەک جار یان زیاتر.CêIT

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

You wroteنووسیتWhat happensچی ڕوو دەداتFixچارەسەر
no count++ in the bodyهیچ count++ـێک لە نییەinfinite loop: the same line for ever: هەمان دێڕ بۆ هەمیشەUpdate the variable in the body. لە ناو نوێ بکەرەوە.
while (i < 3); { … }runs for ever, prints nothing, no warningبۆ هەمیشە کار دەکات، هیچ چاپ ناکات، بێ Delete the ;.;ـەکە بسڕەوە.
} while (i <= 10)';' expectedA do-while ends with );. بە ); کۆتایی دێت.
while (count = 10)incompatible types: int cannot be converted to booleanCompare: count < 10.بەراورد بکە: count < 10.
count = 0; while (count <= 10)11 rounds instead of 10 (real run: Rounds: 11)⁦11⁩ لە جیاتی ⁦10⁩ (جێبەجێکردنی ڕاستەقینە: Rounds: 11)count < 10, or start at 1.count < 10، یان لە 1ـەوە دەست پێ بکە.
sum = 0; inside the loopsum = 0; لە ناو the total restarts every roundکۆکە لە هەموو لە سەرەتاوە دەست پێ دەکاتەوەSet the accumulator before the loop. پێش دابنێ.
do { int n = …; } while (n != 0);cannot find symbolDeclare int n; before do.int n; پێش do بناسێنە.
the sentinel compared as data وەک بەراورد کراوەmax is 0 for negative inputmax is 0 بۆ نەرێنیTest number != 0 first.سەرەتا number != 0 بپشکنە.

The real javac messages of rows 3, 4 and 7:

پەیامە ڕاستەقینەکانی javac بۆ ڕیزەکانی 3، 4 و 7:

Outputدەرئەنجام
$ javac MissingSemicolon.java
MissingSemicolon.java:7: error: ';' expected
        } while (i <= 10)
                         ^
1 error

$ javac AssignInCondition.java
AssignInCondition.java:4: error: incompatible types: int cannot be converted to boolean
        while (count = 10) {
                     ^
1 error

$ javac DoScope.java
DoScope.java:10: error: cannot find symbol
        } while (n != 0);
                 ^
  symbol:   variable n
  location: class DoScope
1 error

Practiceڕاهێنان

ExerciseڕاهێنانTensدەیەکان

Use a while loop to print 10 20 30 … 100 on one line.

بە ⁦10 20 30 … 100⁩ لە یەک دێڕدا چاپ بکە.

Hintئاماژە

Start at 10 and add 10 each round.

لە ⁦10⁩ـەوە دەست پێ بکە و هەر ⁦10⁩ زیاد بکە.

Show answerوەڵامەکە پیشان بدە
Tens.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Tens {
    public static void main(String[] args) {
        int n = 10;
        while (n <= 100) {
            System.out.print(n + " ");
            n += 10;
        }
        System.out.println();
    }
}
ExerciseڕاهێنانSum of the digitsکۆی تاکژمارەکان

Read a whole number and print the sum of its digits (2026 gives 2 + 0 + 2 + 6 = 10).

بخوێنەوە و کۆی چاپ بکە (⁦2026⁩ دەبێتە ⁦2 + 0 + 2 + 6 = 10⁩).

Hintئاماژە

Repeat while n > 0: add n % 10, then n = n / 10.

تا ⁦n > 0⁩ بێت دووپاتە بکەرەوە: ⁦n % 10⁩ زیاد بکە، پاشان ⁦n = n / 10⁩.

Show answerوەڵامەکە پیشان بدە
DigitSum.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class DigitSum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Whole number: ");
        int n = input.nextInt();
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n = n / 10;
        }
        System.out.println("Sum of the digits: " + sum);
    }
}

n % 10 is the last digit and n / 10 drops it (integer division). The loop stops when n reaches 0.

n % 10 دوا و n / 10 لای دەبات (دابەشکردنی ژمارەی تەواو). کاتێک دەوەستێت کە n بگاتە 0.

ExerciseڕاهێنانAsk againدیسان بپرسە

Ask for a mark from 0 to 100 and ask again until it is valid. Test with 150, -3 and 87.

داوای نمرەیەک لە 0 تا ⁦100⁩ بکە و دیسان بپرسە تا دروست بێت. بە ⁦150⁩، ⁦-3⁩ و ⁦87⁩ تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
AskMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class AskMark {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int mark;
        do {
            System.out.print("Mark (0-100): ");
            mark = input.nextInt();
            if (mark < 0 || mark > 100) {
                System.out.println("Not a valid mark.");
            }
        } while (mark < 0 || mark > 100);
        System.out.println("Mark accepted: " + mark);
    }
}

A do-while fits: the question must be asked once before there is anything to check.

گونجاوە: دەبێت پرسیارەکە یەک جار بکرێت پێش ئەوەی شتێک هەبێت بۆ پشکنین.

ExerciseڕاهێنانPast 100تێپەڕاندنی ⁦100⁩

Find the smallest n for which 1 + 2 + … + n is more than 100.

بچووکترین n بدۆزەرەوە کە ⁦1 + 2 + … + n⁩ لە ⁦100⁩ زیاتر بێت.

Show answerوەڵامەکە پیشان بدە
PassHundred.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PassHundred {
    public static void main(String[] args) {
        int n = 0;
        int sum = 0;
        while (sum <= 100) {
            n++;
            sum += n;
        }
        System.out.println("n = " + n + ", sum = " + sum);
    }
}
13⋅142=91≤10014⋅152=105>100\frac{13 \cdot 14}{2} = 91 \le 100 \qquad \frac{14 \cdot 15}{2} = 105 > 100

The formula agrees: 13 is not enough, 14 is.

هاوڕایە: ⁦13⁩ بەس نییە، ⁦14⁩ بەسە.

ExerciseڕاهێنانPredictپێشبینی بکە

What does this print? Write down x after every round.

ئەمە چی چاپ دەکات؟ x لە دوای هەموو بنووسە.

JAVAType in a terminalلە تێرمیناڵدا بینووسە
int x = 1;
while (x < 50) {
    x = x * 3;
}
System.out.println(x);
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
$ java TimesThree
81

x goes 1, 3, 9, 27, 81. The test 81 < 50 is false, so 81 is printed.

x بەم شێوەیە دەڕوات: 1، 3، 9، ⁦27⁩، ⁦81⁩. پشکنینی 81 < 50 هەڵەیە، بۆیە ⁦81⁩ چاپ دەکرێت.

ExerciseڕاهێنانThe sentinel loop with whileخولی پاسەوان بە while

Rewrite TestDoWhile with a while loop. Where must the first number be read?

TestDoWhile بە بنووسەرەوە. دەبێت یەکەم ژمارە لە کوێ بخوێندرێتەوە؟

Hintئاماژە

Read before the loop, and again as the last line of the body.

پێش بخوێنەوە و دیسان وەک دوا دێڕی .

Show answerوەڵامەکە پیشان بدە
SumWhile.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class SumWhile {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int sum = 0;
        System.out.print("Enter an integer (the input ends if it is 0): ");
        int data = input.nextInt();
        while (data != 0) {
            sum += data;
            System.out.print("Enter an integer (the input ends if it is 0): ");
            data = input.nextInt();
        }
        System.out.println("The sum is " + sum);
    }
}

The number is read once before the loop and again at the end of the body, so the test always sees a fresh number. Unlike the do-while version, the 0 is never added.

ژمارەکە یەک جار پێش و دیسان لە کۆتایی دەخوێندرێتەوە، بۆیە پشکنینەکە هەمیشە ژمارەیەکی نوێ دەبینێت. بە پێچەوانەی وەشانی ⁦do-while⁩، 0 هەرگیز کۆ ناکرێتەوە.

Summaryکورتە

  • A loop repeats statements; one pass is one iteration. Java has while, do … while and for.
  • while (condition) { body } tests before every round; the body needs an update, or the loop never ends (stop it with Ctrl+C).
  • Counters count rounds; accumulators collect a total and start at 0 before the loop.
  • do { body } while (condition); runs the body first, at least once, and ends with ;.
  • A sentinel value such as 0 ends the input; it must never be real data.
  • while is a pretest loop (0 or more rounds); do … while is a posttest loop (1 or more).
  • دووپاتە دەکاتەوە؛ هەر تێپەڕبوونێک یەک . Java while، do … while و forـی هەیە.
  • while (condition) { body } پێش هەموو دەپشکنێت؛ پێویستی بە نوێکردنەوە هەیە، ئەگینا هەرگیز کۆتایی نایەت (بە ⁦Ctrl+C⁩ ڕای بگرە).
  • دەژمێرن؛ کۆیەک کۆ دەکەنەوە و پێش لە 0ـەوە دەست پێ دەکەن.
  • do { body } while (condition); سەرەتا جێبەجێ دەکات (لانیکەم یەک جار) و بە ; کۆتایی دێت.
  • وەک 0 کۆتایی بە دەهێنێت؛ نابێت هەرگیز ڕاستەقینە بێت.
  • while (⁦0⁩ یان زیاتر)؛ do … while (⁦1⁩ یان زیاتر).
Review questionsپرسیارەکانی پێداچوونەوە
How many times does while (count < 10) test its condition when count goes from 0 to 10?کاتێک count لە 0ـەوە تا ⁦10⁩ دەڕوات، while (count < 10) چەند جار مەرجەکەی دەپشکنێت؟

11 times: ten times true and a last time false.

⁦11⁩ جار: دە جار ڕاست و دوا جار هەڵە.

Why does while (i < 3); hang?بۆچی while (i < 3); گیر دەخوات و هیچ ناکات؟

The ; is an empty loop body; nothing changes i, so the condition stays true for ever.

;ـەکە خۆی و بەتاڵە؛ هیچ شتێک i ناگۆڕێت، بۆیە بۆ هەمیشە ڕاست دەمێنێتەوە.

When is do-while the better choice?کەی خولی ⁦do...while⁩ هەڵبژاردنی باشترە؟

When the body must run once before the test means anything: reading input, showing a menu.

کاتێک دەبێت یەک جار جێبەجێ بێت پێش ئەوەی پشکنین واتای هەبێت: خوێندنەوەی ، پیشاندانی .

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

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

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

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

The for Loop and Nested Loopsخولی 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 ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.