Loops

The for and while loops: counters, accumulating sums and products.

Java's for loop works like C++'s: start; condition; step. The classic — a counter from 1 to n.
Java

A counter from 1 to 5

The main technique is accumulating the result in a variable. The program below reads n, then n numbers, and computes the sum. The sum is declared as long: with large inputs an int would overflow.
Java

Enter: 4, then 10 20 30 40

The while loop repeats as long as its condition is true — use it when the number of steps is unknown in advance.
Java

How many times is the number divisible by 2? Enter: 96

Task: print all even numbers from 2 to 20 on one line separated by spaces (System.out.print without ln). Then solve the attached problems "Factorial" (compute it in a long!) and "Sum of Array Elements" — and mark the lesson as completed.

Practice problems

Доска