Command Palette

Search for a command to run...

Back to the lesson: Topic 2.9 — Nested Loops and Patterns
Core Java · Example 3 of 4

Counting the work: n² vs pairs

Ten times more input means a hundred times more work: the signature of O(n²).

A loop inside another loop runs its whole inner loop once for every iteration of the outer one. That's how you walk grids, compare every pair, and print patterns, and it's why the work grows as rows × columns (often n²).

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print an inverted right triangle of height 4 using #.

02

Print the numbers 1 to 3 in a 3 × 3 grid where each row repeats its row number (1 1 1, 2 2 2, 3 3 3).

03

Given int[] a = {2, 7, 4, 7, 2, 9}, use nested loops to print every pair of positions that hold equal values.

Explain it without notes

01

If the outer loop runs 5 times and the inner loop runs 4 times, how many times does the inner body run, and why?

02

How do you approach printing a pattern such as a pyramid?

03

Why does the inner loop in for (int j = i + 1; j < n; j++) produce each pair once, and how many iterations does it do?

04

Why should the inner counter be declared in the inner loop's header?

Counting the work: n² vs pairs
Sign in to run this example in your browser.

Expected output

n=10  full=100  pairs=45
n=100  full=10000  pairs=4950
n=1000  full=1000000  pairs=499500