Command Palette

Search for a command to run...

Back to the lesson: Topic 2.6 — The for Loop
Core Java · Example 3 of 4

Two pointers: reverse an array in place

The classic for (init; condition; update) loop puts a loop's start, test and step on one line. It's the standard way to repeat a known number of times or walk through array indexes, and most loop bugs are off-by-one errors in its three parts.

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 the multiplication table of 7 from 7 x 1 to 7 x 10 using a for loop.

02

Given int[] nums = {4, -2, 9, 0, -7, 3}, count how many are positive, negative and zero.

03

Compute 10! (10 factorial) with a for loop. Use a long and explain why.

Explain it without notes

01

In what order do the parts of a for loop run?

02

Why do array loops use i < arr.length rather than i <= arr.length, and what happens if you get it wrong?

03

What is the difference in scope between for (int i = 0; ...) and declaring i before the loop?

04

Why shouldn't you use a double or a byte as a loop counter?

Two pointers: reverse an array in place
Sign in to run this example in your browser.

Expected output

Before: [1, 2, 3, 4, 5, 6]
After:  [6, 5, 4, 3, 2, 1]