Chapter 6b - For Loops
Introducing For Loopsβ
import java.util.*;
class Main {
public static void main(String[] args) {
for(int i = 1; i<3; i++){
System.out.println(i);
}
}
}
note
Animation extracted from Quora
Placing Tablesβ
import java.util.*;
// https://www.geeksforgeeks.org/java-for-loop-with-examples/
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// a simulation of setting the table
System.out.println("Enter number of table placements to be set");
int n = sc.nextInt();
sc.close();
int i;
for(i = 1; i<=n; i++){
System.out.println("Plate placed");
System.out.println("Silverware placed");
System.out.println("Napkin placed");
System.out.println("Glass of water placed");
System.out.println("Table has been set for " + i);
System.out.println();
}
System.out.println("It's dinner time!");
}
}
Try it: for loopsβ
For loops
1 / 2for (int i = 0; i < 5; i++) { ... } β how many times does the body run?
for (int i = 0; i < 5; i++) { ... }
Pick an answer to see if you are right.
Chapter summaryβ
Key takeaways
for (init; condition; update)bundles a loop's setup, its stopping condition, and its per-pass update into one line β reach for it whenever you already know the number of repetitions (or can compute it).- The
initruns once; then Java repeatedly checkscondition, runs the body, and runsupdate, in that order, untilconditionis false. - A
forloop is usually the clearer choice when counting up or down over a known range; awhileloop is usually clearer when you are waiting for something to happen (like valid input). - Nesting a
forloop inside another is exactly how you build grids, tables, and patterns β covered in the next chapter.
Exercisesβ
Activity: Print evens
Read an integer n. Print every even number from 2 up to n (inclusive), one per line, using a for loop.