Repeating a calculation
The loop variable can take part in the calculation. Here the loop adds up 1 + 2 + 3 + ... up to a number from the input:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int last = Integer.valueOf(scanner.nextLine());
int sum = 0;
for (int i = 1; i <= last; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
4Sum: 10Traced, the sum goes 0, 1, 3, 6, 10. The pattern has the same pieces as summing input: a sum that starts at 0 before the loop, and one addition per round. Only now the added value is i itself, or anything calculated from it.