Nested for loops | ICSE Class 9 Computer Applications Notes
On this page
This note covers nested for loops in Java, inner and outer loop control, tracing, square and rectangular patterns, right-angled triangular patterns using numbers and characters, series calculations, and the effects of break and continue.
What is a nested for loop?
Java is the programming language used here. A loop repeats a group of instructions. The word for is a Java keyword, a reserved word that introduces the loop structure used in this note. A control structure determines which instructions execute and in what order. A statement is an instruction in a program. The loop body is the statement or group of statements repeated by the loop. One execution of that body is an iteration.
Definition: A nested loop is a loop contained inside another loop. In a pair of nested for loops, a for loop is placed within the body of another for loop.
The enclosing loop is the outer loop. The enclosed loop is the inner loop. The inner loop is itself part of the outer loop's work. When execution reaches it, it runs according to its own starting value, condition and update.
How are the two loops related?
Flow of control means the order in which statements execute. In ordinary nested counting loops, the outer loop begins an iteration, the inner loop performs its repetitions, and execution then continues through the remaining outer body. The outer loop does not automatically advance after every inner iteration.
A counter is a variable used to track repetitions. A variable is a named storage location whose value can change. Separate counters let the program track the outer and inner repetitions independently. Changing the inner counter need not change the outer counter.
For a printed pattern, the outer loop can select a row, meaning one horizontal line of output. The inner loop can select each position within that row. This arrangement separates the number of rows from the amount of work required to produce each row.
Two loops written one after the other are successive loops, rather than nested loops. To identify nesting, check whether the inner loop is actually inside the outer body. The position of the enclosing braces matters more than how close the loop headings appear on the page.
How is Java syntax used to control nested loops?
Syntax means the rules for writing valid instructions. A block is a group of statements enclosed by the opening brace { and closing brace }. Braces mark the bodies of the loops shown here. Indentation means spaces at the beginning of a line, used to make those bodies clear.
A Java for heading contains initialisation, which establishes a starting value; a condition, which is a true-or-false test; and an update, which changes a value after an iteration. An entry-controlled loop checks its condition before executing its body.
Syntax: for (initialisation; condition; update) { body }
The words inside this template describe the parts to supply; they are not variable names that must be copied.
The semicolon ; separates the three parts of the heading and also ends many individual statements. Parentheses ( ) enclose the heading. The keyword int declares an integer variable, which holds a whole-number value within Java's supported range. The assignment sign = stores the right-hand value in the left-hand variable.
| Notation | Meaning in these programs |
|---|---|
| < | Less than; the two compared values must satisfy this test. |
| <= | Less than or equal to; equality is included in the test. |
| > | Greater than; equality does not satisfy this test. |
| ++ | Increment: increase the counter by one when this update executes. |
| + | Add numeric values, or join text when used with a string. |
| * | Multiply the numeric values on either side. |
What surrounds the loop code?
A class is a Java program structure that groups related data and methods. A method is a named block of instructions. The small classes below use a method named main. The word void means that the method does not return a result to its caller.
The methods use the classroom form void main(), which can be invoked on an object in a suitable teaching environment. An object is an instance of a class. A parameter is a named variable that receives a value when a method is called.
System.out is Java's standard output stream, the destination used here to display text. The dot connects a name to a member. A method call asks a method to run; print displays a value, while println also finishes the current output line.
A string is text enclosed in double quotation marks. Thus " " is one blank space. An empty pair of parentheses in println() supplies no value to print, so the call simply moves subsequent output to a new line.
How can the execution of two nested loops be traced?
A dry run is a manual trace of a program without executing it on a computer. Record the current counters, the result of each condition and the output. Follow execution order rather than reading the loop headings as if they advance together.
In the following program, var1 is the outer counter and var2 is the inner counter. Both begin at zero. Adding one in the output statements displays counting numbers without changing either counter. Parentheses around var1 + 1 make the addition occur before it is joined to text.
Worked example 1. Trace three outer iterations, each containing two inner iterations.
class NestedLoops {
void main() {
for (int var1 = 0; var1 < 3; var1++) {
System.out.println("Iteration " + (var1 + 1) + " of outer loop");
for (int var2 = 0; var2 < 2; var2++) {
System.out.println(var2 + 1);
}
System.out.println("Out of inner loop");
}
System.out.println("Out of outer loop");
}
}Answer: the output is:
Iteration 1 of outer loop
1
2
Out of inner loop
Iteration 2 of outer loop
1
2
Out of inner loop
Iteration 3 of outer loop
1
2
Out of inner loop
Out of outer loop
- The class line opens the program structure; the main line opens the method that performs the trace.
- The outer for line creates var1, starts it at zero, tests whether it is below three and increments it after each completed outer body.
- The first println line announces the current outer iteration using var1 + 1.
- The inner for line creates var2 afresh whenever execution reaches it. It uses the values zero and one.
- The inner println line displays var2 + 1, so the displayed values are one and two, each on its own line.
- The next closing brace ends the inner body. The following println reports that execution has left that loop.
- The outer body's closing brace leads to its update and next condition test. After that loop finishes, the final println reports completion.
- The remaining closing braces end main and the class; they do not print anything.
Result: Three outer iterations with two inner iterations give six inner executions
The inner value output executes six times: two times for each of three outer iterations. The message after the inner loop executes three times. The message after the outer loop executes once. These counts follow from the positions of the statements in the program.
The inner initialisation is therefore not a one-time setup for the whole program. It belongs to each fresh entry into that for statement. Treating its old finishing value as its new starting value would give an incorrect trace.
How do print, println and statement placement shape output?
Tracing counters correctly is only part of predicting output. Output layout also depends on whether each call finishes the line. Several print calls can build one row, while a println call after the inner loop can finish that row before the outer loop begins the next.
If println is used for every value inside the inner loop, the values appear on separate lines. That is suitable for the numbered trace above. To display a pattern across a row, print the values without finishing the line after each one.
Which statements repeat at which level?
| Statement position | When it is reached |
|---|---|
| Before the outer loop | Before any outer iteration begins. |
| Inside the outer body, before the inner loop | Once in each outer iteration that reaches this position. |
| Inside the inner body | During each inner iteration that reaches this statement. |
| After the inner loop, within the outer body | After that inner loop finishes, before the outer iteration ends. |
| After the outer loop | After the outer loop has finished. |
A separator is text placed between displayed items to distinguish them. Printing j + " " joins the value of counter j to a space. That space affects appearance, but it does not create a new line or change the counter.
Rule: To finish a pattern row, place println() after the inner loop's closing brace and before the outer loop's closing brace.
Moving that call outside both loops finishes the line after all rows have been processed. Moving it into the inner body finishes a line after each item. Match each closing brace to its opening brace before deciding which situation a program contains.
When writing an output answer, preserve the order of values and their division into rows. Repeating the correct values in a different arrangement can still describe a different program. State any treatment of trailing spaces separately from the meaningful row content.
How are square and rectangular patterns organised?
A rectangular pattern has a fixed number of rows and the same number of positions in every row. A square pattern has equal row and column counts. A column is a vertical position shared by items in successive rows.
Let rows be the requested row count and columns be the requested number of items per row. Let symbol be the character to display. A character is a single character value, declared with Java's char type in this template.
Here i counts rows and j counts positions within a row. Assume positive counts small enough for these integer counters. The parameters provide the pattern's data; no particular character or dimensions are built into the method.
Syntax: A parameter-based template for a rectangular character pattern.
class CharacterPattern {
void main(int rows, int columns, char symbol) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
System.out.print(symbol);
}
System.out.println();
}
}
}
The class and method lines hold the instructions and declare the three input parameters. The outer for line selects each row. The inner for line visits its positions. The print line displays symbol once per position. The println line finishes the row; the closing braces end the blocks.
What changes for a square or a number pattern?
To make the pattern square, supply equal values for rows and columns. To make each row display counting numbers instead, replace the inner output statement with System.out.print(j + " "). The loop conditions still control the shape; the output expression controls what occupies each position.
For a fixed inner count, the total number of item prints is the row count multiplied by the column count, provided every iteration reaches the print statement. Here both counts are counts of repetitions, so they have no physical unit.
Note: A fixed column limit produces equal row lengths. A limit that depends on the outer counter can produce changing row lengths, so the fixed-count multiplication shortcut must then be reconsidered.
How does a right-angled triangular number pattern work?
A right-angled triangular pattern can be formed by left-aligning rows whose lengths increase one position at a time. Unlike the rectangular template, its inner loop does not use the same fixed limit for every row. The current row number determines how many values appear.
Here num stores the required number of rows, fixed at five. Counter i selects the current row, while j selects the number printed in that row. The condition j <= i includes the current row number as the final value.
Worked example 2. Display five rows, starting with 1 and ending with the row 1 2 3 4 5.
class NumberPattern {
void main() {
int num = 5;
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}Answer: the output has these five rows; each printed number is followed by a space.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
- The class line opens NumberPattern and the main line opens its method.
- The declaration int num = 5 stores the required row count before either loop starts.
- The outer for line starts i at one and includes every row through num.
- The inner for line starts j at one for each row and continues while j is no greater than i.
- The print line displays j followed by a space. Updating j then advances to the next number in the same row.
- The inner closing brace ends its body. The println line, which follows that loop, moves the output to the next row.
- The next brace ends the outer body. Its update increments i; the last two braces end the method and class.
Result: The five-row triangular pattern prints fifteen numbers
| Row counter i | Values printed | Number of item prints |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 2 | 2 |
| 3 | 1 2 3 | 3 |
| 4 | 1 2 3 4 | 4 |
| 5 | 1 2 3 4 5 | 5 |
The total is obtained by adding the row lengths: 1 + 2 + 3 + 4 + 5 = 15. Multiplying five by five would describe five complete rows of five positions. It would not describe this program's changing inner limit.
Printing i in place of j would repeat the row number across that row. Printing a character instead would preserve the triangular arrangement while changing the displayed item. Keep the condition and the output expression separate when explaining shape and content.
The first row checks whether the inner initialisation and inclusive comparison work together. The final row checks whether num is included. Looking at both helps detect a boundary mistake that a middle row alone might not reveal.
What does break do inside nested for loops?
An unlabelled break is a break statement written without a target label. A label is a name attached to a statement to identify it as a possible control target. The unlabelled form used here terminates the nearest enclosing loop when placed inside that loop.
After an inner break, execution continues after the inner loop. Remaining statements in the outer body can still execute. The outer loop has not itself been terminated. Its next iteration can reach and initialise the inner loop again.
In the program below, x is the outer counter and y is the inner counter. Their product is the result of multiplying x by y. An if statement performs its body when its condition is true; here that condition tests whether the product exceeds ten.
Worked example 3. Print products for x from 1 through 3 and y from 2 through 4, ending the current inner loop if the product exceeds 10.
class Products {
void main() {
for (int x = 1; x < 4; x++) {
for (int y = 2; y < 5; y++) {
if (x * y > 10) {
break;
}
System.out.println(x * y);
}
}
}
}Answer: the values are printed on separate lines as follows.
2
3
4
4
6
8
6
9
- The first two lines open the Products class and its main method.
- The outer for line starts x at one, admits values below four and increases x by one after each completed outer iteration.
- The inner for line starts y at two for each x, admits values below five and increases y after ordinary inner iterations.
- The if line tests x * y > 10 before the output statement is reached.
- The break line terminates the inner loop when that test succeeds. The next brace closes the if body.
- The println line displays the product when execution has not already left the inner loop.
- The remaining braces close the inner body, outer body, method and class in that order.
Property: An unlabelled inner break terminates the inner loop
For x equal to one, the products are two, three and four. For x equal to two, they are four, six and eight. For x equal to three, six and nine print, but the next product, twelve, exceeds ten and triggers break before printing.
The inner update is not performed as part of that break. Control leaves the loop instead. This distinction matters when reconstructing a trace: do not add another inner update or output merely because it appears in the normal repetition path.
Rule: Locate the nearest enclosing loop before explaining an unlabelled break. Its effect follows the actual block structure, not the loop whose counter appears in the condition.
How does continue differ from break in a nested loop?
An unlabelled continue skips the remaining statements in the current iteration of the nearest enclosing loop. In a basic Java for loop, control then proceeds to that loop's update, followed by its condition test. It does not restart the loop's initialisation.
When continue belongs to the inner for loop, the outer counter does not advance because of that statement. The inner loop proceeds towards its next iteration. Once the inner loop ends, execution can reach statements that follow it in the outer body.
How can one position be skipped in each row?
In this template, rows and columns are positive integer counts. The parameter skip specifies a position to omit from each row and lies between one and columns. Counter i selects rows and counter j selects positions. The operator == tests whether two values are equal.
Syntax: Skipping a selected position with an inner continue.
class SkipPosition {
void main(int rows, int columns, int skip) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if (j == skip) {
continue;
}
System.out.print(j + " ");
}
System.out.println();
}
}
}
The class and method lines declare the program and its parameters. The outer heading selects a row; the inner heading selects a position. The if line identifies the omitted position. The continue line bypasses printing for that position. The following print line displays each other position.
The inner closing brace ends its body, and println then finishes the row. The remaining braces close the outer body, method and class. Every row displays positions from one through columns except skip, in increasing order. No blank placeholder is printed for the omitted position.
| Effect | Inner break | Inner continue |
|---|---|---|
| Immediate action | Terminates the current inner loop. | Skips the rest of the current inner iteration. |
| Inner update | Not performed as part of leaving through break. | Performed before the next inner condition test. |
| Remaining inner values | Not processed during this entry into the inner loop. | Can still be processed if the condition remains true. |
| Outer loop | Can proceed after the inner loop finishes. | Waits while the inner loop continues. |
Replacing continue with break in this template would stop each row when the selected position is reached. Values after that position would not print. With continue, those later values can print. Both statements must therefore be interpreted together with their location and the statements that follow them.
How can nested loops generate and calculate a series?
A sequence is an ordered list of values. A term is one value in that list. A series is a sum of terms. Nested loops can generate related sequences, display their terms and calculate a separate sum for each outer iteration.
A multiple of a number is obtained by multiplying it by an integer. Let limit be the greatest number whose multiples are required and n be the number of positive multiples required for each number. Both parameters are positive integers.
Here number selects the number whose multiples are being generated, and factor is its positive integer multiplier. Variable term stores their product. Variable sum is an accumulator, meaning a variable that holds a running total.
Syntax: Display the first n positive multiples of each number from one through limit, then display their sum.
class Multiples {
void main(int limit, int n) {
for (int number = 1; number <= limit; number++) {
int sum = 0;
for (int factor = 1; factor <= n; factor++) {
int term = number * factor;
System.out.print(term + " ");
sum = sum + term;
}
System.out.println();
System.out.println(sum);
}
}
}
The class and method lines define the container and input parameters. The outer for line selects number. The sum declaration starts a new total at zero for that number. The inner for line chooses multipliers from one through n.
The term declaration calculates the current product. The print line displays it, and the assignment sum = sum + term adds it to the total already stored. The inner closing brace ends this repeated work. The two println calls finish the terms line and display its total.
Where should an accumulator be initialised?
The final braces close the outer body, method and class. The output alternates a line of multiples with a line containing their sum. Each new outer iteration starts a separate calculation because sum is initialised inside the outer body but before the inner loop.
Placing that initialisation inside the inner body would discard the earlier terms' total on every inner iteration. Placing it before the outer loop would instead allow a cumulative total across different numbers, unless it were reset elsewhere. Its location expresses what the total is intended to include.
Assume the supplied parameters keep the counters, products and sums within the supported int range. Integer overflow means an arithmetic result exceeds that range, so its stored value no longer represents the intended mathematical result. Large unrestricted inputs need separate treatment.
How can a nested-loop program be checked systematically?
A syntax error breaks the language's writing rules. A logical error means the program's instructions do not produce the intended result. Nested-loop work needs both a structure check and an output check: valid Java syntax alone does not establish that the pattern is correct.
Which checks expose common mistakes?
- Match the blocks. Locate the outer opening and closing braces, then locate the inner pair. Check that any row-ending statement is in the intended body.
- List the counter values. Read each initialisation, condition and update. Decide whether the upper limit is included and whether the counter moves towards loop termination.
- Trace a complete outer iteration. Keep the outer value fixed while following the inner loop. Record printed values and any break or continue encountered.
- Restart the inner trace correctly. On the next outer iteration, perform the inner initialisation again when its for statement is reached.
- Check output separately. Mark spaces, line endings and totals. Compare the resulting rows with the required pattern, rather than checking the list of values alone.
An off-by-one error occurs when a count or boundary differs from the intended value by one. In the five-row number triangle, changing an inclusive comparison to a strict comparison would omit an intended final value or row. The initial and final iterations deserve explicit attention.
A semicolon immediately after a for heading can create an empty statement, which does no work, as the loop body. A following block then has a different relationship to the loop from the one suggested by indentation. Inspect punctuation as carefully as counter arithmetic.
A useful trace distinguishes body executions from condition tests. An ordinary loop that ends by a false condition performs a final test that does not lead to another body execution. A break can end the loop earlier, so counting tests mechanically from output is unreliable.
Note: Check the intended scope of every variable and control statement. A variable's scope is the part of the program where its name can be used; a counter declared in a for heading is not available after that loop.
For a complete explanation, connect each line of code to its purpose: selecting rows, generating items, calculating totals, changing control or finishing output. This makes the program's reasoning visible and helps distinguish a correct result from one reached by an accidental arrangement of statements.
Glossary
- Nested loop — A loop placed inside the body of another loop, allowing repeated work within repeated work.
- Outer loop — The enclosing loop whose body contains the inner loop and any surrounding statements.
- Inner loop — The enclosed loop that runs when execution reaches it within the outer body.
- Iteration — One execution of a loop body while the program follows that loop.
- Counter — A variable used to track repetitions, often changed by a loop update.
- Initialisation — The setting of a starting value before a loop begins its condition checks.
- Condition — A true-or-false test used to decide whether a loop body should execute.
- Update — The step that changes a counter after an ordinary for-loop body execution.
- Dry run — A manual record of program execution, including variable values, decisions and output.
- Break — An unlabelled statement that exits the nearest enclosing loop when used within its body.
- Continue — An unlabelled statement that skips the remaining body statements of the nearest loop’s current iteration.
- Accumulator — A variable that stores a running total as successive values are added.
- Scope — The part of a program in which a declared variable name can be used.
- Off-by-one error — A mistake that makes a boundary or repetition count differ from the intended value by one.
Common errors and misconceptions
- Misconception: Both counters advance together after every item. Correct: The inner loop follows its own repetitions while the outer iteration remains in progress; the outer update occurs later.
- Misconception: The inner counter keeps its final value for the next row. Correct: The inner for initialisation runs again whenever execution reaches that for statement, establishing the next row's starting value.
- Misconception: All nested-loop totals can be found by multiplying two fixed counts. Correct: If the inner count changes with the outer value, add the actual inner counts instead.
- Misconception: An inner break terminates both loops. Correct: The unlabelled inner break exits the nearest enclosing loop; the outer loop can still proceed.
- Misconception: Continue restarts the inner initialisation. Correct: In a basic Java for loop, continue moves to its update and next condition test, without repeating that initialisation.
- Misconception: Print and println create identical patterns. Correct: Print keeps subsequent output on the current line; println finishes the line, so its location determines row boundaries.
- Misconception: Indentation by itself defines a Java loop body. Correct: Braces group the statements shown here. Misplaced braces or an extra semicolon can change the structure despite attractive indentation.
- Misconception: A separate row total should be reset inside the inner loop. Correct: Initialise it before that inner loop but within the outer body, so earlier terms in the same row are retained.
Exam-style questions with model answers
Q1. Define a nested loop and identify the relationship between its inner and outer loops. [2 marks]
- A nested loop is a loop placed inside the body of another loop.
- The outer loop encloses the inner loop, which executes when control reaches it during an outer iteration.
Q2. In a Java program, the outer loop uses int var1 = 0; var1 < 3; var1++, and its body contains an inner loop using int var2 = 0; var2 < 2; var2++. The inner body prints var2 + 1 on a separate line. Nothing changes the counters elsewhere, and there is no break or continue. State the outer values, the inner values on each entry and the total number of printed values. [3 marks]
- The outer counter var1 takes the values zero, one and two, because its condition excludes three. There are therefore three outer iterations.
- On each entry, var2 starts at zero and then becomes one. It prints one and two, because the output adds one to its value.
- The inner output executes twice for each of three outer iterations, giving six printed values in total.
Q3. Predict the row contents, row lengths and total number of item prints in this Java method. Explain the new line placement.
void main() {
int num = 5;
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
} [4 marks]
- The five rows are: 1; 1 2; 1 2 3; 1 2 3 4; and 1 2 3 4 5. Semicolons here separate rows.
- The inner counter starts at one for every row and includes i, so the row lengths are one, two, three, four and five.
- Adding those lengths gives fifteen item prints. The changing inner limit means the count is not five multiplied by five.
- The println call follows the inner loop but remains inside the outer body, so it finishes each completed row.
Q4. Write a short Java class with void main() to print exactly five left-aligned rows: 1; 1 2; 1 2 3; 1 2 3 4; 1 2 3 4 5. The semicolons in this question separate rows. Use two nested for loops, a space after each number and a new line after each row. Explain the roles of both counters and both output calls. [5 marks]
- The class below contains a complete method for the requested output. Its braces enclose the method and the two loop bodies.
class NumberPattern {
void main() {
int num = 5;
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
} - The variable num stores five. Counter i selects rows from one through num, so the outer loop creates the required five rows.
- Counter j starts at one whenever the inner loop is entered. Its inclusive condition ends each row with the current value of i.
- The print call displays j followed by a space and keeps the next number on the same output line.
- The println call occurs after the inner loop and finishes one row. The next outer iteration then produces the following row.
Q5. Trace this Java method. State the products printed for each outer value, explain the omitted product and identify the loop terminated by break.
class Products {
void main() {
for (int x = 1; x < 4; x++) {
for (int y = 2; y < 5; y++) {
if (x * y > 10) {
break;
}
System.out.println(x * y);
}
}
}
} [5 marks]
- For x equal to one, y takes two, three and four. The method prints the products two, three and four on separate lines.
- For x equal to two, the inner counter starts at two again. The method prints four, six and eight on separate lines.
- For x equal to three, the first two inner values produce six and nine. Both products satisfy the requirement to continue towards printing.
- The next product is twelve, which exceeds ten. The if condition is true, so break executes before the output statement and twelve is omitted.
- The unlabelled break terminates the inner y loop. Control leaves that loop; it does not terminate the surrounding x loop directly.
Q6. A nested Java for loop prints positions j from 1 through columns for each row i from 1 through rows. Both counters increase by one. rows and columns are positive counts; skip is a position between 1 and columns. Before printing j, the inner body executes if (j == skip) continue;. Explain the output, the next control step and the effect of replacing continue with break. [3 marks]
- Each row displays the positions from one through columns except skip. The continue bypasses the print statement for that selected position.
- Control proceeds to the inner update j++, then tests the inner condition again. It does not repeat the inner initialisation or immediately update i.
- Replacing continue with break would end the current inner loop at skip. Later positions in that row would then be omitted as well.
Q7. For each positive integer number from 1 through limit, a program must print its first n positive multiples and their sum. limit and n are positive integers small enough for int calculations. The outer loop selects number; the inner loop selects factor from 1 through n. Each term is number * factor. Explain where to initialise sum, how to calculate and accumulate each term, where to display the total, and what happens if sum is reset inside the inner loop. [5 marks]
- Initialise sum to zero inside the outer body but before the inner loop. This creates a separate total for each selected number.
- For each inner iteration, calculate term as number multiplied by factor. The multiplier progresses from one through n, including the last requested multiple.
- Print the term and use sum = sum + term to add it to the total retained from earlier inner iterations.
- After the inner loop, finish the line of multiples and print sum. The outer body then ends and the next number can be processed.
- If sum is reset at the start of every inner iteration, previous terms are discarded. After the final addition, it contains only the final term.
Key takeaways
- A nested for loop places an inner loop within an outer loop, allowing repeated work inside each outer iteration.
- Trace the inner loop fully for the current outer value before moving to the outer update.
- The inner initialisation runs again each time execution reaches that for statement within a new outer iteration.
- Fixed inner limits suit rectangular patterns; a limit based on the outer counter can create changing row lengths.
- Use print to build a row and place println after the inner loop to finish that row.
- An unlabelled inner break ends the nearest loop, while continue skips the remainder of its current iteration.
- Initialise a separate row accumulator inside the outer body and before the inner loop that adds its terms.
- Check braces, counter boundaries, jump statements and output layout together before accepting a nested-loop trace.
Test yourself
What makes two loops nested rather than successive?
One loop must lie inside the body of the other, rather than simply follow it.
When is the inner counter initialised again?
Its initialisation runs whenever execution reaches the inner for statement, including on a fresh outer iteration.
In a rectangular pattern, what does the outer loop commonly select?
It selects the current row, while the inner loop visits positions within that row.
Why does j <= i produce changing row lengths when both counters start at one?
The inner upper limit is the current outer value, so each row includes the values from one through i.
Which loop does an unlabelled break inside the inner loop terminate?
It terminates the nearest enclosing loop, which is the inner loop in this arrangement.
What follows an inner continue in a basic Java for loop?
The inner update executes, followed by the inner condition test; the initialisation is not repeated.
Where should println() go to finish each pattern row?
Place it after the inner loop but still within the outer loop body.
Where should sum start at zero if each outer iteration needs its own total?
Initialise sum inside the outer body before the inner loop that calculates and adds the terms.
