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، لەگەڵ خشتەی لێکدان و سێگۆشەیەک لە ئەستێرە و .
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:
کاتێک دەزانیت پێویستی بە چەند هەیە، هەڵبژاردنی ئاساییە. ئەو سێ شتەی هەموو ژماردن پێویستی پێیانە لە یەک دێڕی سەرەدا کۆ دەکاتەوە و بە دوو لە یەکیان جیا دەکاتەوە:
for (initial-action; loop-continuation-condition; action-after-each-iteration) {
// loop body
statement(s);
}- The initial action runs once, before anything else; usually it declares the :
int i = 1. - The is tested before every round:
i <= 10. - The action after each iteration runs after the body, every round:
i++.
- کاری سەرەتا یەک جار جێبەجێ دەبێت، پێش هەموو شتێک؛ زۆرجار دەناسێنێت:
int i = 1. - پێش هەموو دەپشکنرێت:
i <= 10. - کاری دوای هەر دوای لە هەموو جێبەجێ دەبێت:
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 چاپ دەکات، هەر ژمارەیەک لە دێڕێکدا:
public class ForOneToTen {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}$ java ForOneToTen 1 2 3 4 5 6 7 8 9 10
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 یان تاقیگەی بەدواداچوون تاقی بکەرەوە.


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:
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)");
}
}$ java ThreeWays 1 2 3 4 5 (while) 1 2 3 4 5 (for) 1 2 3 4 5 (do-while)
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 تێیدایە (هەڵەی یەکێک زیاتر یان کەمتر).
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);
}
}$ java SumOfFour Enter number 1: 3 Enter number 2: 2 Enter number 3: 6 Enter number 4: 1 sum = 12
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:
دەبێت پێش یان لە کاری سەرەتادا بناسێنرێت. ئەگەر لە سەرەکەدا بناسێنرێت، تەنیا لە ناو هەیە، لە سەرەکەوە تا کەوانەی داخستن، بۆیە بەکارهێنانی لە دوای :
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);
}
}$ javac ForScope.java
ForScope.java:6: error: cannot find symbol
System.out.println("After the loop: i = " + i);
^
symbol: variable i
location: class ForScope
1 errorIf 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.
ئەگەر دوای پێویستت بە هەیە، پێش بناسێنە. ئەگەر تەنیا لە ناو پێویستە، ناساندنی لە سەرەکەدا ڕێگایەکی باشە: لە پێویست زیاتر ناژی، بۆیە دواتر بە هەڵە بەکار نایەت.
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);
}
}$ java ForScopeFixed Inside the loop: i = 0 Inside the loop: i = 1 Inside the loop: i = 2 After the loop: i = 3
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:
کاری سەرەتا دەتوانێت چەند بناسێنێت کە بە کۆما جیا کراونەتەوە و نوێکردنەوەکەش دەتوانێت لیستێک بێت کە بە کۆما جیا کراوەتەوە. دووەمی خوارەوە لە هەردوو سەرەوە بەرەو ناوەڕاست دەڕوات، شێوازێک کە بۆ نموونە بۆ پێچەوانەکردنەوەی دەق بەکار دێت:
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();
}
}$ java CommaLists 0+0 1+1 2+2 3+3 4+4 (1,9) (2,8) (3,7) (4,6)
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 چاپ دەکات.)
public class PrintInHeader {
public static void main(String[] args) {
for (int i = 1; i < 6; System.out.println(i), i++);
}
}$ java PrintInHeader 1 2 3 4 5
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 دەگاتە کۆتایی و هێشتا چاوەڕوانی یەکێکیانە:
public class CommentTrap {
public static void main(String[] args) {
for (int i = 0, j = 0; i + j < 10; i++, j++) { // Do something }
}
}$ javac CommentTrap.java CommentTrap.java:5: error: reached end of file while parsing } ^ 1 error
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 دەژمێرێت و هیچ ناکات؛ پاشان بلۆکەکە یەک جار جێبەجێ دەبێت، وەک بلۆکێکی ئاسایی دوای :
public class ForSemicolon {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++); {
System.out.println("Hello");
}
}
}$ javac -Xlint:all ForSemicolon.java $ java ForSemicolon Hello
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 دوای ئەو دەپشکنێت، بۆیە ـە (پشکنین لە سەرەتا یان لە کۆتایی). لەبەر ئەوەی هەر سێکیان دەتوانن هەموو کارێک بکەن، ئەوەیان هەڵبژێرە کە مەبەستەکەت دەردەبڕێت:
forwhen the number of repetitions is known before the loop starts, such as printing a message 100 times.whilewhen it is not known, such as reading numbers until the input is 0.do … whileinstead ofwhilewhen the body must run before the condition is tested.
forکاتێک ژمارەی دووپاتەکردنەوەکان پێش دەستپێکردنی زانراوە، وەک چاپکردنی پەیامێک 100 جار.whileکاتێک نازانرێت، وەک خوێندنەوەی ژمارەکان تا دەبێتە 0.do … whileلە جیاتیwhileکاتێک دەبێت پێش پشکنینی جێبەجێ بێت.
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)؛ ئەمە یەکەم سەیرکردنە:
public class ForEachFirstLook {
public static void main(String[] args) {
String[] names = {"Aram", "Shilan", "Karwan"};
for (String name : names) {
System.out.println("Hello, " + name + "!");
}
}
}$ java ForEachFirstLook Hello, Aram! Hello, Shilan! Hello, Karwan!
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 جار جێبەجێ دەبێت:
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);
}
}
}
}$ java NestedCount
Outer round 1
inner round 1
inner round 2
inner round 3
Outer round 2
inner round 1
inner round 2
inner round 3A 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", …) بە هەر ژمارەیەک چوار شوێن دەدات، بۆیە ستوونەکان ڕێک دەکەون (پانییەکان):
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();
}
}
}$ java TimesTable 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


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 + " ") نیشانی دەدات:
$ 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 ئەمە دەکات:
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();
}
}
}$ java StarTriangle * ** *** **** *****
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 زیاد دەکات:
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");
}
}$ java OffByOne 1 2 3 4 <- i < 5: 4 rounds 1 2 3 4 5 <- i <= 5: 5 rounds 0 1 2 3 4 5 <- i = 0 and i <= 5: 6 rounds
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 type | Semicolons 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 symbol | Declare 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 parsing | The } on its own line.} لە دێڕی خۆیدا. |
inner loop with int i again ناوەوە دیسان بە int i | variable 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 9 | Change i only in the update.i تەنیا لە نوێکردنەوەکەدا بگۆڕە. |
i < 5 | 5 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:
$ 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ڕاهێنان
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وەڵامەکە پیشان بدە
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);
}
}$ java OddSum 1 + 3 + ... + 99 = 2500
There are 50 odd numbers, and the sum of the first n odd numbers is .
50 ژمارەی تاک هەیە و کۆی یەکەم n ژمارەی تاک دەکاتە .
Compute 10! = 1 × 2 × … × 10 with a for loop.
10! = 1 × 2 × … × 10 بە بژمێرە.
Show answerوەڵامەکە پیشان بدە
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);
}
}$ java Factorial 10! = 3628800
Here the accumulator starts at 1, not 0: multiplying by 0 would destroy the product.
لێرەدا لە 1ـەوە دەست پێ دەکات، نەک 0: لێکدان لە 0 ئەنجامەکە تێک دەدات.
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وەڵامەکە پیشان بدە
public class CountdownFor {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Go!");
}
}$ java CountdownFor 10 9 8 7 6 5 4 3 2 1 Go!
Print a rectangle of # signs, 3 rows and 6 columns, with nested loops.
بە لاکێشەیەک لە نیشانەی # چاپ بکە، 3 ڕیز و 6 ستوون.
Show answerوەڵامەکە پیشان بدە
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();
}
}
}$ java Rectangle ###### ###### ######
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وەڵامەکە پیشان بدە
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();
}
}
}$ java UpsideDown ***** **** *** ** *
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وەڵامەکە پیشان بدە
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");
}
}$ java InnerCount The inner body ran 10 times
1 + 2 + 3 + 4 = 10, because the inner loop runs i times in outer round i.
1 + 2 + 3 + 4 = 10، چونکە ناوەوە لە دەرەوەی iـدا i جار جێبەجێ دەبێت.
Read a number and print its multiplication table from × 1 to × 10.
ژمارەیەک بخوێنەوە و خشتەی لێکدانەکەی لە × 1 تا × 10 چاپ بکە.
Show answerوەڵامەکە پیشان بدە
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));
}
}
}$ java TableOf Which table? 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
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وەڵامەکە پیشان بدە
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);
}
}$ java Backwards banana backwards: ananab Number of a's: 3
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) بژمێرە.
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زاراوە سەرەکییەکان
break and continueڕستەی break و ڕستەی continue
Related lecturesوانە پەیوەندیدارەکان
- break and continueڕستەی break و ڕستەی continue
- Arrays in One and Two Dimensionsڕیزەکەکان لە یەک و دوو ڕەهەنددا
- The for Loop and range()خولی for و
range() - Nested Loops and Patternsخولە ناوەکییەکان و کێشانی شێوە
- for Loops: Sums, Series and Searchingخولەکانی for: کۆکردنەوە، زنجیرە و گەڕان
- Python Next to JavaPython لە تەنیشت Javaـەوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java For Loop
- W3Schools: Java Nested Loops
- W3Schools: Java For-Each Loop
- The Java Tutorials: The for Statement
- Java Language Specification (Java SE 17), §14.14 The for Statement
- Java Language Specification (Java SE 17), §6.3 Scope of a Declaration
- Wikipedia: For loop (the keyword's history: Superplan's für, ALGOL 58)
- Wikipedia: Superplan (Heinz Rutishauser, 1949–1951)
- Wikipedia: ALGOL W (the while statement; Wirth and Hoare, 1966)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.