Back

Activity 5.2 — Array Traversal with for Loops

divider

Introduction

Activity 5.2

Array Traversal with for Loops

Warm-Up Question

  • If an array has 100 elements…
  • Do you really want to type arr[0], arr[1], … arr[99]?
  • Traversal means visiting every element using a loop.

Key Vocabulary (Again)

  • Index: position (starts at 0)
  • Element: value stored at a position
  • Length: number of elements (arr.length)

The One Loop Pattern You Must Know

// Standard array traversal pattern
int[] nums = {4, 7, 2, 9};
for (int i = 0; i < nums.length; i++)
{
System.out.println("Index " + i + " => " + nums[i]);
}
// i is the index (position)
// nums[i] is the element (value at that position)
  • i starts at 0 (first index)
  • loop continues while i < arr.length
  • arr[i] means “element at index i”

Index vs Element

  • i is the index
  • arr[i] is the element
  • Index = where, Element = what

Off-by-One (Most Common Bug)

// Common mistake: off-by-one (DO NOT DO THIS)
int[] nums = {4, 7, 2, 9};
// When i == nums.length, nums[i] is out of bounds
for (int i = 0; i <= nums.length; i++)
{
System.out.println(nums[i]);
}
// Correct condition is: i < nums.length
  • Valid indexes go from 0 to length - 1
  • i < length stops the loop before it breaks

Tracing Example (AP Style)

// Tracing practice: What prints?
int[] a = {10, 20, 30};
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i] + i);
}
// i=0 prints 10+0
// i=1 prints 20+1
// i=2 prints 30+2
  • Before you run code, you should be able to predict output.
  • Write the values of i and what prints each time.

Printing Arrays (Reminder)

// Using import to print arrays nicely
import java.util.Arrays;
int[] nums = {4, 7, 2, 9};
System.out.println(Arrays.toString(nums));
// Without Arrays.toString, printing an array isn't readable.
  • import lets us use helper tools from Java libraries.
  • Arrays.toString(...) converts an array into readable text.
  • Today: you'll mostly print elements in a loop — that's even more readable.

Today's Skills

  • Traverse an array using a for loop
  • Compute a sum and average
  • Count elements that match a condition
  • Find a minimum or maximum value

'F' → Fullscreen

Objectives

  • icon Use a for loop to visit every element in an array.
  • icon Explain why the correct loop condition is i < arr.length.
  • icon Write traversal code that computes a sum/average or count.
  • icon Use traversal to find a minimum and maximum value.
divider

Activity Tasks

  • icon Create a new project named Activity5_2_ArrayTraversal.
  • icon Complete each task in order.
  • icon Use only index-based for loops today (no enhanced for loop yet).

Task 1: Print Every Element

  • icon Traverse an array and print each element.
  • icon Make sure your loop condition uses i < nums.length.
Task 1 — Traversal Basics
public class Program
{
public static void main(String[] args)
{
// Task 1 — Print Every Element (Traversal Basics)
int[] nums = {4, 7, 2, 9, 5};
// Use a for loop to print each element on its own line.
// Example output line: "Value: 4"
for (int i = 0; i < nums.length; i++)
{
System.out.println("Value: " + nums[i]);
}
}
}

Task 2: Sum + Average

  • icon Use a loop to add every score into sum.
  • icon Compute the average as a double.
Task 2 — Sum + Average
public class Program
{
public static void main(String[] args)
{
9 collapsed lines
// Task 1 — Print Every Element (Traversal Basics)
int[] nums = {4, 7, 2, 9, 5};
// Use a for loop to print each element on its own line.
// Example output line: "Value: 4"
for (int i = 0; i < nums.length; i++)
{
System.out.println("Value: " + nums[i]);
}
// Task 2 — Sum + Average
int[] scores = {84, 91, 76, 88, 95};
int sum = 0;
// Add every element into sum
for (int i = 0; i < scores.length; i++)
{
sum += scores[i];
}
double avg = (double) sum / scores.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
}
}

Task 3: Count Values Meeting a Condition

  • icon Count how many items match a rule using an if inside the loop.
  • icon This pattern shows up constantly on AP-style questions.
Task 3 — Counting
public class Program
{
public static void main(String[] args)
{
26 collapsed lines
// Task 1 — Print Every Element (Traversal Basics)
int[] nums = {4, 7, 2, 9, 5};
// Use a for loop to print each element on its own line.
// Example output line: "Value: 4"
for (int i = 0; i < nums.length; i++)
{
System.out.println("Value: " + nums[i]);
}
// Task 2 — Sum + Average
int[] scores = {84, 91, 76, 88, 95};
int sum = 0;
// Add every element into sum
for (int i = 0; i < scores.length; i++)
{
sum += scores[i];
}
double avg = (double) sum / scores.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
// Task 3 — Count Values Meeting a Condition
int[] temps = {72, 68, 75, 70, 69, 76, 71};
// Count how many temps are 72 or higher
int count = 0;
for (int i = 0; i < temps.length; i++)
{
if (temps[i] >= 72)
{
count++;
}
}
System.out.println("Temps >= 72: " + count);
}
}

Task 4: Find Min and Max

  • icon Initialize min and max to the first element.
  • icon Traverse from index 1 to the end, updating as needed.
Task 4 — Min/Max
public class Program
{
public static void main(String[] args)
{
43 collapsed lines
// Task 1 — Print Every Element (Traversal Basics)
int[] nums = {4, 7, 2, 9, 5};
// Use a for loop to print each element on its own line.
// Example output line: "Value: 4"
for (int i = 0; i < nums.length; i++)
{
System.out.println("Value: " + nums[i]);
}
// Task 2 — Sum + Average
int[] scores = {84, 91, 76, 88, 95};
int sum = 0;
// Add every element into sum
for (int i = 0; i < scores.length; i++)
{
sum += scores[i];
}
double avg = (double) sum / scores.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
// Task 3 — Count Values Meeting a Condition
int[] temps = {72, 68, 75, 70, 69, 76, 71};
// Count how many temps are 72 or higher
int count = 0;
for (int i = 0; i < temps.length; i++)
{
if (temps[i] >= 72)
{
count++;
}
}
System.out.println("Temps >= 72: " + count);
// Task 4 — Find Min and Max (Classic AP Pattern)
int[] nums = {4, 7, 2, 9, 5};
// Start min and max at the first element
int min = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < min)
{
min = nums[i];
}
if (nums[i] > max)
{
max = nums[i];
}
}
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
divider

Sample Output

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

Sample Output
Value: 4
Value: 7
Value: 2
Value: 9
Value: 5
Sum: 434
Average: 86.8
Temps >= 72: 3
Min: 2
Max: 9
divider

Reflection Questions

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

  1. In one sentence: what does it mean to traverse an array?
  2. Why is i < arr.length correct, but i <= arr.length is not?
  3. What is the difference between i and arr[i]?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete