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

The for Loop and Nested Loopsخولی for و خولە ناوەکییەکان

Java's counting loop: the three parts of a for header, counting 1 to 10, the same loop written three ways, reading four numbers, the loop variable that lives only in the loop, comma lists and the one-line comment trap, a semicolon after the header, which loop to choose, a first look at for-each, nested loops with a multiplication table and a star triangle, and off-by-one errors.

ژماردنی Java: سێ بەشەکەی سەرەی for، ژماردن لە 1 تا ⁦10⁩، هەمان بە سێ ڕێگا، خوێندنەوەی چوار ژمارە، کە تەنیا لە ناو دەژی، لیستی کۆمایی و تەڵەی لە یەک دێڕدا، لە دوای سەرەکە، کام هەڵبژێریت، یەکەم سەیرکردنی ⁦for-each⁩، لەگەڵ خشتەی لێکدان و سێگۆشەیەک لە ئەستێرە و .

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

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

  • Write a for loop and say how often its start, condition, body and update run.
  • Explain where the loop variable can be used, and avoid the ; and // traps.
  • Choose between for, while and do-while, and rewrite one loop as another.
  • Use nested loops for tables and patterns, and check the edges against off-by-one errors.
  • بنووسیت و بڵێیت سەرەتا، ، و نوێکردنەوەکەی چەند جار جێبەجێ دەبن.
  • ڕوونی بکەیتەوە لە کوێ بەکار دێت و خۆت لە تەڵەکانی ; و // بپارێزیت.
  • لە نێوان for، while و ⁦do-while⁩ـدا هەڵبژێریت و بە شێوەیەکی تر بنووسیتەوە.
  • بۆ خشتە و نەخشە بەکار بهێنیت و سنوورەکان لە دژی بپشکنیت.

The three parts of a for headerسێ بەشەکەی سەرەی خولی for

When you know how many rounds a loop needs, the is the usual choice. It puts the three things every counting loop needs into one header line, separated by two semicolons:

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

The shape of a for loopشێوەی خولی forTEXT
for (initial-action; loop-continuation-condition; action-after-each-iteration) {
    // loop body
    statement(s);
}
The header for (int i = 1; i <= 10; i++) { with its three parts in coloured boxes and arrows from three labels: 1 initial action, runs once before the loop; 2 condition, tested before every round; 3 update, runs after the body every round. Below, the body System.out.println(i); runs while the condition is true. Two semicolons separate the parts; there is none after the ).سەرەی for (int i = 1; i <= 10; i++) { بە سێ بەشەکەیەوە لە سندووقی ڕەنگاوڕەنگدا و تیر لە سێ نووسینەوە: 1 کاری سەرەتا، یەک جار پێش خولەکە؛ 2 مەرج، پێش هەموو خولانەوەیەک دەپشکنرێت؛ 3 نوێکردنەوە، دوای جەستەی خولەکە لە هەموو خولانەوەیەکدا. لە خوارەوە جەستەی خولەکە System.out.println(i); تا مەرجەکە ڕاست بێت جێبەجێ دەبێت. دوو خاڵبۆر بەشەکان جیا دەکەنەوە؛ لە دوای کەوانەی داخستن هیچ خاڵبۆرێک نییە.
Start once, test before every round, update after every roundسەرەتا یەک جار، پشکنین پێش هەموو ، نوێکردنەوە دوای هەموو CêIT
  1. The initial action runs once, before anything else; usually it declares the : int i = 1.
  2. The is tested before every round: i <= 10.
  3. The action after each iteration runs after the body, every round: i++.
  1. کاری سەرەتا یەک جار جێبەجێ دەبێت، پێش هەموو شتێک؛ زۆرجار دەناسێنێت: int i = 1.
  2. پێش هەموو دەپشکنرێت: i <= 10.
  3. کاری دوای هەر دوای لە هەموو جێبەجێ دەبێت: i++.

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

Read a for loop aloud and it sounds like an English sentence. for (int i = 1; i <= 10; i++) means “for each value of i from 1 to 10, do this”, the way a mathematician writes “for i = 1, 2, …, 10”. The keyword names what the loop does: it goes through a list of values, one for each round.

ئەگەر بە دەنگی بەرز بخوێنیتەوە، وەک ڕستەیەکی ئینگلیزی دەردەکەوێت. for (int i = 1; i <= 10; i++) واتە «بۆ هەر بەهایەکی i لە 1ـەوە تا ⁦10⁩، ئەمە بکە»، هەروەک بیرکاریزانێک دەنووسێت «بۆ ⁦i = 1⁩، 2، …، ⁦10⁩». کاری دەڵێت: بە لیستێکی بەهادا تێدەپەڕێت، یەکێک بۆ هەر .

The word comes from German. Between 1949 and 1951 the Swiss mathematician Heinz Rutishauser designed Superplan, one of the first programming languages, and wrote its loop with the German word für (“for”). When ALGOL 58 and ALGOL 60 were designed, with Rutishauser among the authors, the loop kept the idea in English: for. Most later languages, among them C, Java, PHP, Python and MATLAB, use the same English word. (FORTRAN, from the same years, called its loop DO.) The whole story of the word is in the Honame section of the for loop term page.

وشەکە لە ئەڵمانییەوە هاتووە. لە نێوان ساڵانی ⁦1949⁩ و ⁦1951⁩دا، بیرکاریزانی سویسری هاینز ڕوتیسهاوزەر (Heinz Rutishauser) Superplanـی دیزاین کرد، کە یەکێک بوو لە یەکەم و بە وشەی ئەڵمانیی für («بۆ») نووسی. کاتێک ⁦ALGOL 58⁩ و ⁦ALGOL 60⁩ دیزاین کران و ڕوتیسهاوزەر یەکێک بوو لە نووسەرانیان، هەمان بیرۆکەی بە ئینگلیزی پاراست: for. زۆربەی ئەو زمانانەی دواتر هاتن، لەوانە C، Java، PHP، Python و MATLAB، هەمان وشە ئینگلیزییە بەکاردەهێنن. (FORTRAN، کە لە هەمان سەردەمدا بوو، ناوی نابوو DO.) هەموو چیرۆکی وشەکە لە بەشی «هۆنامە»ی پەڕەی زاراوەی خولی forدایە.

Counting from 1 to 10ژماردن لە 1 تا ⁦10⁩

This program prints 1 to 10, one number per line:

ئەم 1 تا ⁦10⁩ چاپ دەکات، هەر ژمارەیەک لە دێڕێکدا:

ForOneToTen.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForOneToTen {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

The animation follows a shorter version with i <= 3 (it prints Round 1 to Round 3, then Done): start once, then test, body and update, again and again, until the test is false. To follow a for loop in a table, see Tracing a for loop or try the trace lab.

ئەنیمەیشنەکە وەشانێکی کورتتر بە i <= 3 بەدوادا دەچێت (Round 1 تا Round 3 و پاشان Done چاپ دەکات): سەرەتا یەک جار، پاشان پشکنین، و نوێکردنەوە، دووپاتە و دووپاتە، تا پشکنینەکە هەڵە دەبێت. بۆ بەدواداچوونی لە خشتەیەکدا، بڕوانە بەدواداچوونی خولی for یان تاقیگەی بەدواداچوون تاقی بکەرەوە.

An animation of for (int i = 1; i <= 3; i++) { System.out.println("Round " + i); } followed by System.out.println("Done");. One part lights up at a time: int i = 1 once; then the test i <= 3, the body that prints Round 1, and i++; again for 2 and 3; then 4 <= 3 is false and Done is printed. A row of four chips, 1 start, 2 test, 3 body, 4 update, shows the order, with an arrow back to 2 test.
An animation of for (int i = 1; i <= 3; i++) { System.out.println("Round " + i); } followed by System.out.println("Done");. One part lights up at a time: int i = 1 once; then the test i <= 3, the body that prints Round 1, and i++; again for 2 and 3; then 4 <= 3 is false and Done is printed. A row of four chips, 1 start, 2 test, 3 body, 4 update, shows the order, with an arrow back to 2 test.
Start once; then test, body, update, test …سەرەتا یەک جار؛ پاشان پشکنین، ، نوێکردنەوە، پشکنین …CêIT

One loop, three waysخولێک، سێ ڕێگا

The three loops are equally powerful: any loop can be written in all three forms, so you can use whichever is clearest for the job. Here is the same count from 1 to 5 as while, for and do … while:

سێ وەک یەک بەهێزن: هەر دەتوانرێت بە هەر سێ شێوەکە بنووسرێت، بۆیە دەتوانیت ڕوونترینیان بۆ کارەکە بەکار بهێنیت. ئەمە هەمان ژماردنی 1 تا 5ـە بە while، for و do … while:

ThreeWays.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ThreeWays {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.print(i + " ");
            i++;
        }
        System.out.println("(while)");

        for (int j = 1; j <= 5; j++) {
            System.out.print(j + " ");
        }
        System.out.println("(for)");

        int k = 1;
        do {
            System.out.print(k + " ");
            k++;
        } while (k <= 5);
        System.out.println("(do-while)");
    }
}
Three code panels, while, for and do … while, each printing 1 2 3 4 5. The same four parts have the same colours in all three: the start value int i = 1 (blue), the condition i <= 5 (orange), the body System.out.print (green) and the update i++ (purple). In the for loop the start, the condition and the update share one header line.سێ تابلۆی کۆد، while، for و do … while، هەریەکە 1 2 3 4 5 چاپ دەکات. هەمان چوار بەش لە هەر سێکیاندا هەمان ڕەنگیان هەیە: نرخی سەرەتا int i = 1 (شین)، مەرجەکە i <= 5 (پرتەقاڵی)، جەستەی خولەکە System.out.print (سەوز) و نوێکردنەوەی i++ (مۆر). لە خولی forـدا سەرەتا، مەرج و نوێکردنەوە لە یەک دێڕی سەرەدان.
The same start, test, body and update in three shapesهەمان سەرەتا، پشکنین، و نوێکردنەوە بە سێ شێوەCêIT

The loops use i, j and k because i from the while loop still exists after it. A second int i in the for header stops javac with variable i is already defined in method main(String[]); a variable declared in a for header disappears after its loop (next screens).

i، j و k بەکار دەهێنن، چونکە iـی دوای ئەویش هەر هەیە. int iـێکی تر لە سەرەی forـدا javac بە variable i is already defined in method main(String[]) دەوەستێنێت؛ کە لە ناو سەرەی forـدا بناسێنرێت دوای نامێنێت (شاشەکانی دواتر).

Adding four numbers from the keyboardکۆکردنەوەی چوار ژمارە لە کیبۆردەوە

A for loop can read input too. This program asks for four whole numbers and adds them up with an accumulator (accumulator). The header for (int i = 1; i < 5; i++) runs for i = 1, 2, 3 and 4: four rounds, although 5 appears in it (off by one).

دەتوانێت بخوێنێتەوە. ئەم داوای چوار دەکات و بە کۆیان دەکاتەوە (گۆڕاوی کۆکردنەوە). سەرەی for (int i = 1; i < 5; i++) بۆ ⁦i = 1⁩، 2، 3 و 4 جێبەجێ دەبێت: چوار ، هەرچەندە 5 تێیدایە (هەڵەی یەکێک زیاتر یان کەمتر).

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

public class SumOfFour {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int sum = 0;
        for (int i = 1; i < 5; i++) {
            System.out.print("Enter number " + i + ": ");
            int n = input.nextInt();
            sum += n;
        }
        System.out.println("sum = " + sum);
    }
}

n is declared inside the body, so a new n is made in every round; only sum must live outside the loop.

n لە ناو ناسێنراوە، بۆیە لە هەموو nـێکی نوێ دروست دەکرێت؛ تەنیا sum دەبێت لە دەرەوەی بژی.

The loop variable lives only in the loopگۆڕاوی خول تەنیا لە ناو خولەکەدا دەژی

The control variable must be declared before the loop or in its initial action. Declared in the header, it exists only inside the loop, from the header to the closing brace, so using it after the loop is a compile error:

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

ForScope.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForScope {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println("Inside the loop: i = " + i);
        }
        System.out.println("After the loop: i = " + i);
    }
}

If you need the value after the loop, declare the variable before it. If you need it only inside, declaring it in the header is good practice: it lives no longer than necessary, so it cannot be misused later.

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

ForScopeFixed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForScopeFixed {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 3; i++) {
            System.out.println("Inside the loop: i = " + i);
        }
        System.out.println("After the loop: i = " + i);
    }
}
Two programs. Left: for (int i = 0; i < 3; i++) { … } followed by System.out.println("After: " + i); the loop lines are highlighted, the last line is marked with a cross and error: cannot find symbol. Right: int i; before the loop, so all lines are highlighted and the last line prints After: 3.دوو بەرنامە. چەپ: for (int i = 0; i < 3; i++) { … } و لە دوایدا System.out.println("After: " + i)؛ دێڕەکانی خولەکە ڕەنگ کراون، دوا دێڕ نیشانەی هەڵەی پێوەیە و error: cannot find symbol. ڕاست: int i; پێش خولەکە، بۆیە هەموو دێڕەکان ڕەنگ کراون و دوا دێڕ After: 3 چاپ دەکات.
Declared in the header: gone after the loopلە سەرەدا ناسێنرا: دوای نامێنێتCêIT

This rule is called (more in Block scope). Python keeps the loop variable after the loop (Where a variable lives).

ئەم یاسایە پێی دەوترێت (زیاتر لە مەودای بلۆک). Python دوای دەهێڵێتەوە (گۆڕاوێک لە کوێ دەژی).

Several variables in one headerچەند گۆڕاوێک لە یەک سەرەدا

The initial action can declare several variables, separated by commas, and the update can be a comma separated list too. The second loop below walks from both ends towards the middle, a pattern used, for example, to reverse text:

کاری سەرەتا دەتوانێت چەند بناسێنێت کە بە کۆما جیا کراونەتەوە و نوێکردنەوەکەش دەتوانێت لیستێک بێت کە بە کۆما جیا کراوەتەوە. دووەمی خوارەوە لە هەردوو سەرەوە بەرەو ناوەڕاست دەڕوات، شێوازێک کە بۆ نموونە بۆ پێچەوانەکردنەوەی دەق بەکار دێت:

CommaLists.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CommaLists {
    public static void main(String[] args) {
        for (int i = 0, j = 0; i + j < 10; i++, j++) {
            System.out.print(i + "+" + j + " ");
        }
        System.out.println();
        for (int left = 1, right = 9; left < right; left++, right--) {
            System.out.print("(" + left + "," + right + ") ");
        }
        System.out.println();
    }
}

The update can even hold the work itself. This header prints the numbers and leaves the loop an empty body, just ;. It is legal, but hard to read; normal code puts System.out.println(i); in the body. (With i < 100 the same line prints 1 to 99.)

نوێکردنەوەکە تەنانەت دەتوانێت خودی کارەکەشی تێدا بێت. ئەم سەرەیە ژمارەکان چاپ دەکات و بەتاڵ دەهێڵێتەوە، تەنیا ;. ڕێگەپێدراوە، بەڵام خوێندنەوەی قورسە؛ کۆدی ئاسایی System.out.println(i); دەخاتە ناو . (بە i < 100 هەمان دێڕ 1 تا ⁦99⁩ چاپ دەکات.)

PrintInHeader.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PrintInHeader {
    public static void main(String[] args) {
        for (int i = 1; i < 6; System.out.println(i), i++);
    }
}

Several variables in one headerچەند گۆڕاوێک لە یەک سەرەدا

The one-line comment trapتەڵەی لێدوان لە یەک دێڕدا

Typed on one line, for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something } does not compile. A // comment runs to the end of the line, so the closing } belongs to the comment. The braces no longer match, and javac reaches the end of the file still waiting for one:

ئەگەر لە یەک دێڕدا بنووسرێت، for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something } کۆمپایل نابێت. بە // تا کۆتایی دێڕەکە دەڕوات، بۆیە }ـی داخستن سەر بە . کەوانەکان ئیتر یەک ناگرنەوە و javac دەگاتە کۆتایی و هێشتا چاوەڕوانی یەکێکیانە:

CommentTrap.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CommentTrap {
    public static void main(String[] args) {
        for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something }
    }
}
The one-line header for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something } with the comment part shaded and an arrow to its } : this } is part of the comment. Below, the real javac message: CommentTrap.java:5: error: reached end of file while parsing. Then the fix: the comment and the } on their own lines.سەرەی یەک دێڕی for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something } و بەشی لێدوانەکە سێبەر کراوە و تیرێک بۆ }ـەکەی: ئەم }ـە بەشێکە لە لێدوانەکە. لە خوارەوە پەیامی ڕاستەقینەی javac: CommentTrap.java:5: error: reached end of file while parsing. پاشان چارەسەر: لێدوانەکە و } هەریەکە لە دێڕی خۆیدا.
A // comment swallows the rest of the line, brace and all بە // باقی دێڕەکە قووت دەدات، کەوانەکەشەوەCêIT

Put the comment and the } on separate lines (Line and block comments), or use /* … */, which ends where you close it.

و } لە دوو دێڕی جیادا بنووسە (لێدوانەکان بە دێڕ و بە بلۆک)، یان /* … */ بەکار بهێنە کە لەو شوێنە کۆتایی دێت کە دایدەخەیت.

Several variables in one headerچەند گۆڕاوێک لە یەک سەرەدا

A semicolon after the headerخاڵبۆر لە دوای سەرەکە

Written by mistake, the same ; gives a surprise: the block after the header is then not the loop body at all. The loop counts to 3 doing nothing; then the block runs once, as an ordinary block after the loop:

ئەگەر بە هەڵە بنووسرێت، هەمان ; سەرت سوڕ دەهێنێت: ئەوکات دوای سەرەکە هیچ پەیوەندی بە نییە. تا 3 دەژمێرێت و هیچ ناکات؛ پاشان بلۆکەکە یەک جار جێبەجێ دەبێت، وەک بلۆکێکی ئاسایی دوای :

ForSemicolon.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForSemicolon {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++); {
            System.out.println("Hello");
        }
    }
}
The code for (int i = 1; i <= 3; i++); { System.out.println("Hello"); } with the semicolon highlighted. Step 1: the loop runs 3 times with an empty body. Step 2: the block runs once, as a normal block after the loop. The terminal shows Hello once, not three times. javac gives no warning, even with -Xlint:all; if the block uses i, javac says cannot find symbol.کۆدی for (int i = 1; i <= 3; i++); { System.out.println("Hello"); } و خاڵبۆرەکە ڕەنگ کراوە. هەنگاوی 1: خولەکە 3 جار دەسوڕێتەوە و جەستەی خولەکە بەتاڵە. هەنگاوی 2: بلۆکەکە یەک جار جێبەجێ دەبێت، وەک بلۆکێکی ئاسایی دوای خولەکە. تێرمیناڵەکە Hello یەک جار پیشان دەدات، نەک سێ جار. javac هیچ هۆشدارییەک نادات، تەنانەت بە -Xlint:all؛ ئەگەر بلۆکەکە i بەکار بهێنێت، javac دەڵێت cannot find symbol.
Hello once: the block is not the loop bodyHello یەک جار: بلۆکەکە نییەCêIT

javac gives no warning, even with -Xlint:all. If the block uses i, the mistake at least shows: i belongs to the loop, so javac reports cannot find symbol.

javac هیچ نادات، تەنانەت بە -Xlint:all. ئەگەر بلۆکەکە i بەکار بهێنێت، هەڵەکە بەلایەنی کەمەوە دەردەکەوێت: i سەر بە ، بۆیە javac cannot find symbol ڕاپۆرت دەکات.

Which loop?کام خول؟

while and for test before the body, so they are ; do … while tests after it, so it is a (Test first or test last). Since all three can do every job, choose the one that says what you mean:

while و for پێش دەپشکنن، بۆیە ؛ do … while دوای ئەو دەپشکنێت، بۆیە ـە (پشکنین لە سەرەتا یان لە کۆتایی). لەبەر ئەوەی هەر سێکیان دەتوانن هەموو کارێک بکەن، ئەوەیان هەڵبژێرە کە مەبەستەکەت دەردەبڕێت:

  • for when the number of repetitions is known before the loop starts, such as printing a message 100 times.
  • while when it is not known, such as reading numbers until the input is 0.
  • do … while instead of while when the body must run before the condition is tested.
  • for کاتێک ژمارەی دووپاتەکردنەوەکان پێش دەستپێکردنی زانراوە، وەک چاپکردنی پەیامێک ⁦100⁩ جار.
  • while کاتێک نازانرێت، وەک خوێندنەوەی ژمارەکان تا دەبێتە 0.
  • do … while لە جیاتی while کاتێک دەبێت پێش پشکنینی جێبەجێ بێت.
A decision chart. First question: do you know the number of rounds before the loop starts? Yes leads to for (e.g. print 100 lines). No leads to a second question: must the body run at least once, before the first test? Yes leads to do … while (e.g. show a menu, then ask); no leads to while (read until 0). All three can do every job; choose the clearest one.هێڵکارییەکی بڕیاردان. یەکەم پرسیار: پێش دەستپێکردن ژمارەی خولانەوەکان دەزانیت؟ بەڵێ دەچێت بۆ for (وەک چاپکردنی 100 دێڕ). نەخێر دەچێت بۆ پرسیاری دووەم: دەبێت جەستەی خولەکە لانیکەم یەک جار، پێش یەکەم پشکنین، جێبەجێ بێت؟ بەڵێ دەچێت بۆ do … while (وەک پیشاندانی مێنیو، پاشان پرسیار)؛ نەخێر دەچێت بۆ while (تا 0 بخوێنەوە). هەر سێکیان دەتوانن هەموو کارێک بکەن؛ ڕوونترینیان هەڵبژێرە.
Two questions pick the clearest loopدوو پرسیار ڕوونترین هەڵدەبژێرنCêIT

A first look at the for-each loopیەکەم سەیرکردنی خولی foreach

Java has a second form of for for collections, the (also called the enhanced for). It hands you every item of an array or a list in turn, with no counter and no index. Arrays come later, with more for-each (The for-each loop); here is a first look:

Java شێوەیەکی دووەمی forـی بۆ کۆکراوەکان هەیە: (پێی دەوترێت enhanced forـیش). هەموو یان لیستێک یەک لە دوای یەک دەداتە دەستت، بێ و بێ . دواتر دێن، لەگەڵ زیاتر لە ⁦for-each⁩ (خولی foreach)؛ ئەمە یەکەم سەیرکردنە:

ForEachFirstLook.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForEachFirstLook {
    public static void main(String[] args) {
        String[] names = {"Aram", "Shilan", "Karwan"};
        for (String name : names) {
            System.out.println("Hello, " + name + "!");
        }
    }
}
The header for (String name : names) above three boxes "Aram", "Shilan" and "Karwan" in an array called names. An arrow from each box gives its value to the variable name, in round 1, round 2 and round 3.سەرەی for (String name : names) لە سەرووی سێ سندووقی "Aram"، "Shilan" و "Karwan" لە ڕیزەکێکدا بە ناوی names. تیرێک لە هەر سندووقێکەوە نرخەکەی دەداتە گۆڕاوەکە name، لە خولانەوە 1، خولانەوە 2 و خولانەوە 3ـدا.
Each round, name gets the next itemلە هەر name دانەی دواتر وەردەگرێتCêIT

Read the header as "for each String name in names". Use it when you need every item in order but not its position; for positions, or to change the items, use the counting for.

سەرەکە وا بخوێنەوە: «بۆ هەر String nameـێک لە ناو names». کاتێک پێویستت بە هەموو دانەکان بە ڕیز هەیە، بەڵام نەک بە شوێنیان، بەکاری بهێنە؛ بۆ شوێنەکان یان بۆ گۆڕینی دانەکان، forـی ژماردن بەکار بهێنە.

A loop inside a loopخول لە ناو خولدا

A loop can stand inside another loop: a . For every round of the outer loop, the inner loop runs completely, from its start to its end. With 2 outer rounds and 3 inner rounds, the inner body runs 2 × 3 = 6 times:

دەتوانێت لە ناو تردا بێت: . بۆ هەر دەرەوە، ناوەوە بە تەواوی جێبەجێ دەبێت، لە سەرەتاوە تا کۆتایی. بە 2 دەرەوە و 3 ناوەوە، ناوەوە ⁦2 × 3 = 6⁩ جار جێبەجێ دەبێت:

NestedCount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class NestedCount {
    public static void main(String[] args) {
        for (int i = 1; i <= 2; i++) {
            System.out.println("Outer round " + i);
            for (int j = 1; j <= 3; j++) {
                System.out.println("    inner round " + j);
            }
        }
    }
}
Two large boxes, outer round i = 1 and outer round i = 2. Inside each are three smaller boxes, j = 1, j = 2 and j = 3, the inner rounds: the inner loop runs to the end in each outer round. 2 outer rounds × 3 inner rounds = 6 inner rounds.دوو سندووقی گەورە، خولانەوەی دەرەوە i = 1 و خولانەوەی دەرەوە i = 2. لە ناو هەریەکەیاندا سێ سندووقی بچووکتر، j = 1، j = 2 و j = 3، خولانەوەکانی ناوەوە: خولی ناوەوە لە هەر خولانەوەیەکی دەرەوەدا تا کۆتایی جێبەجێ دەبێت. 2 خولانەوەی دەرەوە × 3 خولانەوەی ناوەوە = 6 خولانەوەی ناوەوە.
The inner loop starts again in every outer round ناوەوە لە هەموو دەرەوەدا دیسان دەست پێ دەکاتەوەCêIT

A multiplication tableخشتەی لێکدان

Rows and columns are a natural job for nested loops: the outer loop picks the row i, the inner loop fills the columns j, and System.out.println() after the inner loop ends the row. printf("%4d", …) gives every number four places, so the columns line up (Widths):

ڕیز و ستوون کارێکی سروشتیی : دەرەوە ڕیزی i هەڵدەبژێرێت، ناوەوە ستوونەکانی j پڕ دەکاتەوە و System.out.println() لە دوای ناوەوە ڕیزەکە تەواو دەکات. printf("%4d", …) بە هەر ژمارەیەک چوار شوێن دەدات، بۆیە ستوونەکان ڕێک دەکەون (پانییەکان):

TimesTable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class TimesTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.printf("%4d", i * j);
            }
            System.out.println();
        }
    }
}
A 5 by 5 grid fills up next to the TimesTable code. With i = 1 the inner loop fills the first row cell by cell: 1, 2, 3, 4, 5, and println() ends the line. Then, for i = 2 to 5, the inner loop runs again from j = 1 to 5 and a whole row appears each time. Finally: 5 outer rounds × 5 inner rounds = 25 products.
A 5 by 5 grid fills up next to the TimesTable code. With i = 1 the inner loop fills the first row cell by cell: 1, 2, 3, 4, 5, and println() ends the line. Then, for i = 2 to 5, the inner loop runs again from j = 1 to 5 and a whole row appears each time. Finally: 5 outer rounds × 5 inner rounds = 25 products.
The inner loop fills a row; the outer loop moves down ناوەوە ڕیزێک پڕ دەکاتەوە؛ دەرەوە دادەبەزێتCêIT

Without printf the columns slip as soon as the numbers get two digits, as this real run of the same loops with print(i * j + " ") shows:

بەبێ printf هەر کە ژمارەکان دوو دەبن ستوونەکان دەخزێن، وەک ئەم جێبەجێکردنە ڕاستەقینەیەی هەمان بە print(i * j + " ") نیشانی دەدات:

Outputدەرئەنجام
$ java TimesTablePlain
1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 

Patterns: a triangle of starsنەخشە: سێگۆشەیەک لە ئەستێرە

When the end of the inner loop depends on the outer variable, the rows grow: row 1 prints one star, row 5 prints five. The inner condition star <= row does it:

کاتێک کۆتایی ناوەوە بەستراوە بە دەرەوە، ڕیزەکان گەورە دەبن: ڕیزی 1 یەک ئەستێرە چاپ دەکات و ڕیزی 5 پێنج. ناوەوە star <= row ئەمە دەکات:

StarTriangle.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class StarTriangle {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int star = 1; star <= row; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Rows 1 to 5 with 1, 2, 3, 4 and 5 stars and, for each row, the inner condition star <= 1 … star <= 5. Beside them the nested loops, with the line star <= row highlighted. The end of the inner loop depends on the outer variable.ڕیزەکانی 1 تا 5 بە 1، 2، 3، 4 و 5 ئەستێرە و بۆ هەر ڕیزێک مەرجی ناوەوە star <= 1 … star <= 5. لە تەنیشتیانەوە خولە ناوەکییەکان، دێڕی star <= row ڕەنگ کراوە. کۆتایی خولی ناوەوە بەستراوە بە گۆڕاوی دەرەوە.
Row r gets r stars because the inner loop stops at star <= rowڕیزی r ژمارەی r ئەستێرە وەردەگرێت چونکە ناوەوە لە ⁦star <= row⁩ دەوەستێتCêIT

The Python track follows the same triangle with a trace table, one row per inner round (A trace table with one row per inner round).

ڕێڕەوی Python هەمان سێگۆشە بە بەدوادا دەچێت، بۆ هەر ناوەوە ڕیزێک (خشتەیەکی بەدواداچوون بە ڕیزێک بۆ هەر خولانەوەیەکی ناوەوە).

Off by one: < or <=هەڵەی یەکێک زیاتر یان کەمتر: < یان <=

The most common loop bug is one round too many or too few: an . Compare the headers: i < 5 stops at 4, i <= 5 includes 5, and starting at 0 adds a round:

باوترین یەک زیاتر یان کەمترە: . سەرەکان بەراورد بکە: i < 5 لە 4ـدا دەوەستێت، i <= 5 5ـیش دەگرێتەوە و دەستپێکردن لە 0 زیاد دەکات:

OffByOne.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class OffByOne {
    public static void main(String[] args) {
        int rounds = 0;
        for (int i = 1; i < 5; i++) {
            System.out.print(i + " ");
            rounds++;
        }
        System.out.println("  <- i < 5: " + rounds + " rounds");

        rounds = 0;
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
            rounds++;
        }
        System.out.println("  <- i <= 5: " + rounds + " rounds");

        rounds = 0;
        for (int i = 0; i <= 5; i++) {
            System.out.print(i + " ");
            rounds++;
        }
        System.out.println("  <- i = 0 and i <= 5: " + rounds + " rounds");
    }
}
Five fence posts numbered 1 to 5 with rails between them: 4 gaps of fence need 5 posts. Below, three rows: for (int i = 1; i < 5; i++) gives 1 2 3 4, 4 rounds; for (int i = 1; i <= 5; i++) gives 1 2 3 4 5, 5 rounds; for (int i = 0; i <= 5; i++) gives 0 1 2 3 4 5, 6 rounds. Count the rounds: last - first + 1 with <=, last - first with <.پێنج ستوونی پەرژین بە ژمارەی 1 تا 5 و تەختەی نێوانیان: 4 بەشی پەرژین 5 ستوونیان پێویستە. لە خوارەوە سێ ڕیز: for (int i = 1; i < 5; i++) دەداتە 1 2 3 4، 4 خولانەوە؛ for (int i = 1; i <= 5; i++) دەداتە 1 2 3 4 5، 5 خولانەوە؛ for (int i = 0; i <= 5; i++) دەداتە 0 1 2 3 4 5، 6 خولانەوە. خولانەوەکان بژمێرە: لەگەڵ <= دوایین − یەکەم + 1، لەگەڵ < دوایین − یەکەم.
Fence posts and gaps: the classic off-by-one pictureستوون و بەشەکانی پەرژین: وێنە ناسراوەکەی CêIT

Count the rounds before you run: with <= it is last − first + 1, with < it is last − first. A fence with 4 gaps needs 5 posts, which is why the mistake is also called a fencepost error. The trace lab has an off-by-one loop to find and fix.

پێش جێبەجێکردن بژمێرە: لەگەڵ <= دوایین − یەکەم + 1، لەگەڵ < دوایین − یەکەم. پەرژینێک بە 4 بەش 5 ستوونی پێویستە، بۆیە ئەم هەڵەیە بە ئینگلیزی fencepost errorـیشی پێ دەوترێت. تاقیگەی بەدواداچوون هەڵەی یەکێک زیاتر یان کەمتری تێدایە بۆ دۆزینەوە و چاککردن.

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

You wroteنووسیتjavac or the run saysjavac یان جێبەجێکردن دەڵێتFixچارەسەر
for (int i = 0, i < 5, i++)';' expected illegal start of typeSemicolons between the three parts. لە نێوان سێ بەشەکەدا.
for (i = 0; i < 3; i++)cannot find symbol, once for every icannot find symbol، بۆ هەر iـێک یەک جارDeclare it: int i = 0.بیناسێنە: int i = 0.
i used after the loopi لە دوای بەکارهاتووەcannot find symbolDeclare int i; before the loop.int i; پێش بناسێنە.
for (…); { … }the block runs once, after the loop; no warningبلۆکەکە یەک جار جێبەجێ دەبێت، دوای ؛ بێ Delete the ;.;ـەکە بسڕەوە.
{ // comment }reached end of file while parsingThe } on its own line.} لە دێڕی خۆیدا.
inner loop with int i again ناوەوە دیسان بە int ivariable i is already defined in method main(String[])Use j for the inner loop.بۆ ناوەوە j بەکار بهێنە.
i++ in the body as welli++ هەروەها لە ناو numbers are skipped: 1 3 5 7 9ژمارەکان تێدەپەڕێنرێن: 1 3 5 7 9Change i only in the update.i تەنیا لە نوێکردنەوەکەدا بگۆڕە.
i < 55 is missing: one round too few5 نییە: یەک کەمترi <= 5 when 5 belongs in.i <= 5 کاتێک 5 دەبێت تێیدا بێت.

Real javac messages for rows 1 and 6, and the real run of row 7:

پەیامە ڕاستەقینەکانی javac بۆ ڕیزەکانی 1 و 6 و جێبەجێکردنی ڕاستەقینەی ڕیزی 7:

Outputدەرئەنجام
$ javac CommasWrong.java
CommasWrong.java:3: error: ';' expected
        for (int i = 0, i < 5, i++) {
                         ^
CommasWrong.java:3: error: illegal start of type
        for (int i = 0, i < 5, i++) {
                            ^
2 errors

$ javac SameVariable.java
SameVariable.java:4: error: variable i is already defined in method main(String[])
            for (int i = 1; i <= 3; i++) {
                     ^
1 error

$ java ChangeLoopVariable
1 3 5 7 9 

Practiceڕاهێنان

ExerciseڕاهێنانOdd numbersژمارە تاکەکان

Add the odd numbers 1 + 3 + 5 + … + 99 with a for loop.

ژمارە تاکەکانی ⁦1 + 3 + 5 + … + 99⁩ بە کۆ بکەرەوە.

Hintئاماژە

Start at 1 and use i += 2.

لە 1ـەوە دەست پێ بکە و i += 2 بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
OddSum.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class OddSum {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 99; i += 2) {
            sum += i;
        }
        System.out.println("1 + 3 + ... + 99 = " + sum);
    }
}
1+3+5+⋯+99=502=25001 + 3 + 5 + \cdots + 99 = 50^2 = 2500

There are 50 odd numbers, and the sum of the first n odd numbers is n2n^2.

⁦50⁩ ژمارەی تاک هەیە و کۆی یەکەم n ژمارەی تاک دەکاتە n2n^2.

Exerciseڕاهێنان10 factorialفاکتۆریاڵی ⁦10⁩

Compute 10! = 1 × 2 × … × 10 with a for loop.

⁦10! = 1 × 2 × … × 10⁩ بە بژمێرە.

Show answerوەڵامەکە پیشان بدە
Factorial.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Factorial {
    public static void main(String[] args) {
        int factorial = 1;
        for (int k = 1; k <= 10; k++) {
            factorial *= k;
        }
        System.out.println("10! = " + factorial);
    }
}

Here the accumulator starts at 1, not 0: multiplying by 0 would destroy the product.

لێرەدا لە 1ـەوە دەست پێ دەکات، نەک 0: لێکدان لە 0 ئەنجامەکە تێک دەدات.

ExerciseڕاهێنانCountdownژماردنی پێچەوانە

Print 10 9 8 … 1 and then Go! on one line, with a for loop.

بە لە یەک دێڕدا ⁦10 9 8 … 1⁩ و پاشان Go! چاپ بکە.

Hintئاماژە

Start at 10, test i >= 1, update i--.

لە ⁦10⁩ـەوە دەست پێ بکە، i >= 1 بپشکنە، i-- نوێ بکەرەوە.

Show answerوەڵامەکە پیشان بدە
CountdownFor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CountdownFor {
    public static void main(String[] args) {
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println("Go!");
    }
}
ExerciseڕاهێنانA rectangleلاکێشەیەک

Print a rectangle of # signs, 3 rows and 6 columns, with nested loops.

بە لاکێشەیەک لە نیشانەی # چاپ بکە، 3 ڕیز و 6 ستوون.

Show answerوەڵامەکە پیشان بدە
Rectangle.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Rectangle {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 6; col++) {
                System.out.print("#");
            }
            System.out.println();
        }
    }
}
ExerciseڕاهێنانUpside downسەرەوخوار

Print the star triangle upside down: 5 stars first, 1 star last.

سێگۆشە ئەستێرەکە سەرەوخوار چاپ بکە: یەکەم جار 5 ئەستێرە و کۆتا جار 1 ئەستێرە.

Hintئاماژە

Let the outer loop count down: row = 5; row >= 1; row--.

با دەرەوە بە پێچەوانە بژمێرێت: row = 5; row >= 1; row--.

Show answerوەڵامەکە پیشان بدە
UpsideDown.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class UpsideDown {
    public static void main(String[] args) {
        for (int row = 5; row >= 1; row--) {
            for (int star = 1; star <= row; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
ExerciseڕاهێنانCount the inner roundsژماردنی خولانەوەکانی ناوەوە

How many times does the inner body run in for (int i = 1; i <= 4; i++) for (int j = 1; j <= i; j++)? Work it out, then check with a counter.

لە for (int i = 1; i <= 4; i++) for (int j = 1; j <= i; j++)ـدا ناوەوە چەند جار جێبەجێ دەبێت؟ بیژمێرە، پاشان بە پشکنینی بکە.

Show answerوەڵامەکە پیشان بدە
InnerCount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class InnerCount {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                count++;
            }
        }
        System.out.println("The inner body ran " + count + " times");
    }
}

1 + 2 + 3 + 4 = 10, because the inner loop runs i times in outer round i.

⁦1 + 2 + 3 + 4 = 10⁩، چونکە ناوەوە لە دەرەوەی iـدا i جار جێبەجێ دەبێت.

ExerciseڕاهێنانOne times tableیەک خشتەی لێکدان

Read a number and print its multiplication table from × 1 to × 10.

ژمارەیەک بخوێنەوە و خشتەی لێکدانەکەی لە × 1 تا × ⁦10⁩ چاپ بکە.

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

public class TableOf {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Which table? ");
        int n = input.nextInt();
        for (int i = 1; i <= 10; i++) {
            System.out.println(n + " x " + i + " = " + (n * i));
        }
    }
}
ExerciseڕاهێنانLetters one by oneپیت بە پیت

Use a for loop that counts down over the positions of "banana" to print the word backwards and to count its letter a (charAt and length).

بەکار بهێنە کە بە پێچەوانە بە سەر شوێنەکانی "banana"ـدا دەڕوات، بۆ ئەوەی وشەکە بە پێچەوانە چاپ بکەیت و پیتی aـی تێدا بژمێریت (charAt و length).

Hintئاماژە

Start at word.length() - 1, stop after 0, and read each letter with charAt(i).

لە word.length() - 1ـەوە دەست پێ بکە، دوای 0 بوەستە و هەر پیتێک بە charAt(i) بخوێنەوە.

Show answerوەڵامەکە پیشان بدە
Backwards.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Backwards {
    public static void main(String[] args) {
        String word = "banana";
        String backwards = "";
        int count = 0;
        for (int i = word.length() - 1; i >= 0; i--) {
            char c = word.charAt(i);
            backwards += c;
            if (c == 'a') {
                count++;
            }
        }
        System.out.println(word + " backwards: " + backwards);
        System.out.println("Number of a's: " + count);
    }
}

The last position is length() - 1, because positions start at 0. Adding each char to backwards builds the word the other way round.

دوا شوێن length() - 1ـە، چونکە شوێنەکان لە 0ـەوە دەست پێ دەکەن. زیادکردنی هەر charـێک بۆ backwards وشەکە بە پێچەوانە دروست دەکات.

Strings: Practice counts the a's of banana without a loop (with replace and the lengths) and turns a word round with StringBuilder: compare the two ways.

زنجیرەنووسەکان: ڕاهێنان ژمارەی aـکانی banana بەبێ دەژمێرێت (بە replace و درێژییەکان) و وشەیەک بە StringBuilder پێچەوانە دەکاتەوە: هەردوو ڕێگاکە بەراورد بکە.

Summaryکورتە

  • for (start; condition; update) { body }: the start runs once, the condition before every round, the update after every round.
  • A variable declared in the header lives only in the loop (block scope); declare it before the loop to keep it.
  • No ; after the header, and no // comment in front of a }.
  • All three loops can do every job: for for a known count, while otherwise, do-while when the body must run once first.
  • In nested loops the inner loop runs completely in every outer round: outer × inner rounds.
  • Check the edges: < or <=, start at 0 or 1. Count last − first (+ 1).
  • for (start; condition; update) { body }: سەرەتا یەک جار، پێش هەموو و نوێکردنەوە دوای هەموو جێبەجێ دەبن.
  • کە لە سەرەدا ناسێنرابێت تەنیا لە ناو دەژی ()؛ بۆ هێشتنەوەی، پێش بیناسێنە.
  • هیچ ;ـێک لە دوای سەرەکە مەنووسە و هیچ بە // لە پێش }ـێک دامەنێ.
  • هەر سێ دەتوانن هەموو کارێک بکەن: for بۆ ژمارەیەکی زانراو، while بۆ باقی و ⁦do-while⁩ کاتێک دەبێت سەرەتا یەک جار جێبەجێ بێت.
  • لە ناوەوە لە هەموو دەرەوەدا بە تەواوی جێبەجێ دەبێت: دەرەوە × ناوەوە.
  • سنوورەکان بپشکنە: < یان <=، دەستپێک لە 0 یان 1. دوایین − یەکەم ⁦(+ 1)⁩ بژمێرە.
Review questionsپرسیارەکانی پێداچوونەوە
How many times is the condition of for (int i = 1; i <= 10; i++) tested?مەرجی for (int i = 1; i <= 10; i++) چەند جار دەپشکنرێت؟

11 times: true for 1 to 10, false for 11.

⁦11⁩ جار: بۆ 1 تا ⁦10⁩ ڕاست، بۆ ⁦11⁩ هەڵە.

Why can't you print the loop variable i after for (int i = 0; …)?بۆچی ناتوانیت گۆڕاوی خولەکە i لە دوای for (int i = 0; …) چاپ بکەیت؟

Its scope ends with the loop; javac says cannot find symbol.

لەگەڵ کۆتایی دێت؛ javac دەڵێت cannot find symbol.

An outer loop runs 3 times and the inner loop 4 times. How often does the inner body run?خولی دەرەوە 3 جار و خولی ناوەوە 4 جار جێبەجێ دەبن. جەستەی خولی ناوەوە چەند جار جێبەجێ دەبێت؟

12 times (3 × 4).

⁦12⁩ جار ⁦(3 × 4)⁩.

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

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

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

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

break and continueڕستەی break و ڕستەی continue

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.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.