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
forloop 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
whileloop to count down: printcount, then take 1 off, whilecountis 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
ifthat doesbreakwheniis 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
forloop to add every number from 1 to 100 tototal.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
forloop to print the even numbers from 1 to 10.Add each even number to
suminside the loop. After the loop, print"Sum: " + sum.
More in Java Loops & Arrays
Previous: Conditionals · Next: Arrays