Skip to main content

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​

Quiz

For loops

1 / 2

for (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
  1. 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).
  2. The init runs once; then Java repeatedly checks condition, runs the body, and runs update, in that order, until condition is false.
  3. A for loop is usually the clearer choice when counting up or down over a known range; a while loop is usually clearer when you are waiting for something to happen (like valid input).
  4. Nesting a for loop 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.