Coding for All
Lesson 18: For Loop Addition
For Loop Addition Add up every number in an array.
1public static void main(String[] args) {
2 int[] arr = {1, 2, 3};
3 int total = 0;
4 for (int i = 0; i < arr.length; i++) {
5 total += arr[i];
6 }
7 System.out.println(total);
8}
Terminal
$ javac Main.java
$ java Main
6
Every line, explained
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
int[] arr = {1, 2, 3};
An int[] array holding the three numbers we want to add up.
int total = 0;
int declares a variable that stores a whole number (an "integer") like 1, 5 or 1000. The = sign stores the value on the right into the variable named on the left, and the semicolon ; ends the statement, like a full stop at the end of a sentence. total starts at 0 and will collect the running sum.
for (int i = 0; i < arr.length; i++) {
A for loop repeats code. Its three parts are separated by semicolons: int i = 0 creates the counter, i < arr.length keeps looping while that is true, and i++ adds 1 to the counter after every trip. Note that arr.length has no parentheses: for arrays, length is a built-in value, not a method.
total += arr[i];
+= adds the value on the right onto the variable on the left. total += arr[i]; is a shorter way of writing total = total + arr[i]; The loop adds arr[0], then arr[1], then arr[2] onto total: 0+1=1, 1+2=3, 3+3=6.
}
This } closes the for loop. Everything between the loop's { and } is repeated on every trip around the loop.
System.out.println(total);
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". By the time the loop has finished, total is 6.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.