- Write
for,whileanddo-whileloops and choose between them - Control a loop with
breakandcontinue - Create an array, read and change its elements, and find their sum and maximum
Imagine you have to print a greeting for each of the 30 students in a class. You could write println 30 times — but what if there were 3000 students? Computers are great at repeating the same work without getting tired, and that is what loops are for. To keep many values in one place, we use arrays.
for and while loops
A for loop is handy when you know the number of steps in advance. Its header has three parts: the start (int i = 1), the condition (i <= 5) and the step (i++). A while loop repeats as long as its condition is true — it suits cases where you do not know how many repetitions there will be.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
for (int i = 2; i <= 10; i += 2) {
sum += i;
}
System.out.println("Sum of even numbers: " + sum);
int balance = 100;
int years = 0;
while (balance < 200) {
balance += balance / 10;
years++;
}
System.out.println(years + " years, balance " + balance);
}
}1 2 3 4 5 Sum of even numbers: 30 8 years, balance 212
In the last part, Elvin puts 100 manats in a bank, and each year 10% is added to the amount. We do not know how many years he has to wait, so we use a while loop: it keeps going until the balance reaches 200. balance / 10 is integer division, so each year's interest is rounded down to whole manats.
int in the program throws away the fractions every year.do-while, break and continue
A do-while loop checks its condition at the end, so its body runs at least once even if the condition is false. break ends the loop immediately, while continue skips the rest of the current step and moves on to the next one.
public class Main {
public static void main(String[] args) {
int tries = 0;
do {
tries++;
System.out.println("Attempt " + tries);
} while (tries < 0);
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue;
}
if (i > 7) {
break;
}
System.out.print(i + " ");
}
System.out.println();
}
}Attempt 1 1 2 4 5 7
The condition tries < 0 is false from the start, yet “Attempt 1” was still printed. In the second loop, 3 and 6 were skipped by continue, and at 8 break stopped the loop completely, so 9 and 10 were never printed.
Arrays
An object that holds a fixed number of values of the same type in order. Elements are accessed by an index starting at 0, and the array's length cannot change after it is created.
public class Main {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 64, 99};
System.out.println("First: " + scores[0]);
System.out.println("Count: " + scores.length);
scores[3] = 70;
int sum = 0;
int max = scores[0];
for (int s : scores) {
sum += s;
if (s > max) {
max = s;
}
}
System.out.println("Average: " + (double) sum / scores.length);
System.out.println("Max: " + max);
String[] days = new String[3];
System.out.println(days[0]);
double[] temps = new double[2];
System.out.println(temps[1]);
}
}First: 85 Count: 5 Average: 84.8 Max: 99 null 0.0
int[] scores = {85, 92, ...};creates an array with ready values;new String[3]creates an array with 3 empty slots.scores.lengthis the number of elements (no parentheses — it is a field, not a method).for (int s : scores)is a for-each loop: it hands each element of the array tosin turn.- A new array is filled automatically: numbers get
0or0.0,booleangetsfalse, and objects (such asString) getnull.
The Arrays class and 2D arrays
The java.util.Arrays class has ready-made tools for arrays: Arrays.toString() turns an array into readable text, and Arrays.sort() puts the elements in ascending order. An array's elements can themselves be arrays — such a two-dimensional array works like a table: the first index is the row and the second is the column.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {42, 7, 19, 3, 25};
System.out.println(Arrays.toString(nums));
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
int[][] table = new int[3][4];
for (int r = 0; r < table.length; r++) {
for (int c = 0; c < table[r].length; c++) {
table[r][c] = (r + 1) * (c + 1);
}
}
for (int[] row : table) {
System.out.println(Arrays.toString(row));
}
System.out.println(table[2][3]);
}
}[42, 7, 19, 3, 25] [3, 7, 19, 25, 42] [1, 2, 3, 4] [2, 4, 6, 8] [3, 6, 9, 12] 12
Key points
for (start; condition; step)is used when the number of steps is known,whileto repeat until a condition changes.do-whilechecks its condition at the end and runs the body at least once.breakends the loop;continuejumps to the next step.- An array has a fixed length, and its indexes go from 0 to
length - 1. Arrays.toString()helps you print an array, andArrays.sort()sorts it.
Check yourself
10 questions. Every correct answer earns XP.
for (int i = 0; i < 4; i++) repeat?