Back

Activity 2.8 For Loops

divider

Introduction

Activity 2.8

For Loops

Topics

  • Introduction to For Loops
  • Components of a For Loop
  • While Loop vs. For Loop

Introduction to For Loops

Java offers several loop constructs to handle iteration. Although the while loop is flexible enough for most iterative tasks, other loops can often achieve the same results with code that is more concise or logically structured.

Introduction to For Loops

One essential construct is the for loop. While it is functionally similar to a while loop, its syntax groups the key control elements together.

for (int i = 1; i <= 10; i++)
{
System.out.println(i);
}

Components of a For Loop

A for loop consists of three main expressions, separated by semicolons, within the parentheses, in addition to the for keyword and the code block:

for (int i = 1; i <= 10; i++)
{
System.out.println(i);
}
  1. Initialization (int i = 1;): Executed once at the beginning of the loop.
  2. Condition (i <= 10;): A logical expression evaluated before each iteration.
  3. Update (i++): Executed at the end of each iteration.

For Loop Animation

Converting a Simple While Loop to a For Loop

Demo: Counting Down

for (int i = 10; i >= 1; i--)
{
System.out.println(i);
}

Demo: Counting Evens

for (int i = 2; i <= 10; i += 2)
{
System.out.println(i);
}

While Loop vs. For Loop

The following tips can help you decide which loop to use, but they're not strict rules. Choose the approach that best fits your specific task and makes your code easier to understand.

Use a for loop when you know ahead of time how many times the loop should run. This is ideal for situations with a fixed number of iterations, like looping through a list or counting a range of numbers.

Use a while loop when the number of iterations isn't known in advance. This works well when you're waiting for a condition to be met, such as user input.

Key Terms

For Loop
A control structure designed for definite iteration (repetition) where the number of cycles is typically known before the loop begins. Its syntax groups the control variables in one line.

'F' → Fullscreen

Objectives

  • icon Iteration with For Loops
divider

Activity Tasks

  • icon Create a new project named 2-8-For-Loops.
  • icon Complete each task individually.

Task 1: Printing Multiples

Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Counting Multiples ---");
System.out.print("Choose a number: ");
int number = input.nextInt();
System.out.print("List how many multiples of " + number + "? ");
int count = input.nextInt();
int sum = number; // Sum is used to keep track of current multiple
for (int i = 0; i < count; i++)
{
System.out.print(sum + " "); // Display horizontally
sum += number;
}
input.nextLine(); // Consume newline
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
}
}

Task 2: Squares Table

Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
22 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Counting Multiples ---");
System.out.print("Choose a number: ");
int number = input.nextInt();
System.out.print("List how many multiples of " + number + "? ");
int count = input.nextInt();
int sum = number; // Sum is used to keep track of current multiple
for (int i = 0; i < count; i++)
{
System.out.print(sum + " "); // Display horizontally
sum += number;
}
input.nextLine(); // Consume newline
System.out.print("\nPress enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2 - Square Tables ---");
System.out.print("Enter row count: ");
int rows = input.nextInt();
System.out.println("\nNumber\tSquare");
System.out.println("----------------");
for (int i = 1; i <= rows; i++)
{
System.out.println(i + "\t" + (i * i));
}
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1 - Counting Multiples ---
Choose a number: 5
List how many multiples of 5? 10
5 10 15 20 25 30 35 40 45 50
Press enter to continue...
--- Demo 2 - Square Tables ---
Enter row count: 12
Number Square
----------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Based on the difference between for and while loops explained in the Introduction, why might the for loop a better structural choice for both the "Counting Multiples" and "Square Tables" demos?
  2. In the "Counting Multiples" task, the for loop variable i starts at 0. If you wanted the loop to start counting from i = 1, what specific change would you need to make to the Condition part of the loop's header, and why?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete