Loops

Programming Languages · Java Loops & Arrays · 12 min

Repeat code with for and while loops, stop early, and add things up.

The for loop

A loop repeats code so you don't have to copy it. A for loop has three parts: where to start, when to keep going, and how to step.

for (int i = 1; i <= 3; i++) {
    System.out.println(i);
}
// prints 1, 2, 3

i++ means "add 1 to i".

  • Use a for loop to print the numbers 1 to 5, one per line.

The while loop

A while loop keeps going as long as its condition is true. It's handy when you don't know in advance how many rounds you need.

Remember to change the variable inside, or the loop never ends!

int n = 1;
while (n < 100) {
    n = n * 2;
}
  • Use a while loop to count down: print count, then take 1 off, while count is above 0.

  • After the loop, print Liftoff!

for-each: one item at a time

pets below is an array, a list of values (more on those next lesson). A for-each loop visits every item in order. Read the colon as "in": for each pet in pets.

for (String pet : pets) {
    System.out.println(pet);
}
  • Use a for-each loop to print every name in names.

Stopping early: break

break jumps out of a loop straight away, even if it had more rounds to go. It's often used with an if.

for (int i = 1; i <= 100; i++) {
    if (i == 3) {
        break;
    }
    System.out.println(i);
}
// prints 1, 2
  • Inside the loop, before the print, add an if that does break when i is 4.

A running total

A common trick: start a variable at 0, then add to it on every round of the loop. When the loop ends, it holds the total. total += i is short for total = total + i.

int total = 0;
for (int i = 1; i <= 3; i++) {
    total += i;
}
// total is 6
  • Use a for loop to add every number from 1 to 100 to total.

  • After the loop, print total.

Put it together: even numbers

Loop from 1 to 10. Print only the even numbers and add them up as you go.

Tip: i % 2 is the remainder after dividing by 2, so i % 2 == 0 means i is even.

  • Use a for loop to print the even numbers from 1 to 10.

  • Add each even number to sum inside the loop. After the loop, print "Sum: " + sum.

More in Java Loops & Arrays

Previous: Conditionals · Next: Arrays