Lesson 12 • Intermediate

Arrays

30 minutes
Data Structures

📦 What are Arrays?

Arrays are collections that store multiple values of the same type under a single variable name. Instead of creating separate variables for each item, you can store them all in one array and access them by index.

Why Use Arrays?
Imagine storing test scores for 100 students. Without arrays, you'd need: score1, score2, score3... score100 (100 variables!)

With an array: scores[100] (One array, 100 values!)

Arrays make it easy to:
  • Store multiple related values
  • Process data using loops
  • Organize collections of information

Visual: Array Memory Layout

scores[5]
Index 0
85
Index 1
92
Index 2
78
Index 3
95
Index 4
88
🔢 Indices
0, 1, 2, 3, 4
📊 Values
85, 92, 78, 95, 88

📐 Array Declaration

# Declare array with size
var arrayName[size]

# Declare and initialize
var numbers = [10, 20, 30, 40, 50]
Example: Basic Array Declaration
Algorithm ArrayBasics

# Declare an array for 5 scores
var scores[5]

# Assign values to array elements
scores[0] = 85
scores[1] = 92
scores[2] = 78
scores[3] = 95
scores[4] = 88

# Access and display values
Print "First score:", scores[0]
Print "Third score:", scores[2]
Print "Last score:", scores[4]

Endalgorithm
Output
First score: 85 Third score: 78 Last score: 88
Array Indexing Starts at 0!
Arrays use zero-based indexing:
  • First element: array[0]
  • Second element: array[1]
  • Third element: array[2]
  • Last element of size 5: array[4]

🔄 Looping Through Arrays

Arrays and loops work perfectly together:

Example: Array with FOR Loop
Algorithm ArrayLoop

var numbers[5]

# Fill array with values
Print "Filling array..."
For i = 0 To 4
    numbers[i] = (i + 1) * 10
    Print "numbers[", i, "] =", numbers[i]
Endfor

# Calculate sum
var sum = 0
For i = 0 To 4
    sum = sum + numbers[i]
Endfor

Print ""
Print "Sum of all elements:", sum
Print "Average:", sum / 5

Endalgorithm

📏 Size() Function

Use Size() to get the number of elements in an array:

Example: Using Size()
Algorithm ArraySize

var scores = [85, 92, 78, 95, 88]

var arraySize = Size(scores)
Print "Array size:", arraySize

# Loop through array using Size()
Print ""
Print "All scores:"
For i = 0 To Size(scores) - 1
    Print "Score", i + 1, ":", scores[i]
Endfor

Endalgorithm

Common Array Operations

1. Find Maximum

Example: Find Maximum Value
Algorithm FindMaximum

var numbers = [45, 23, 89, 12, 67, 34]

var max = numbers[0]  # Start with first element
var maxIndex = 0

For i = 1 To Size(numbers) - 1
    If numbers[i] > max Then
        max = numbers[i]
        maxIndex = i
    Endif
Endfor

Print "Maximum value:", max
Print "Found at index:", maxIndex

Endalgorithm

2. Find Minimum

Example: Find Minimum Value
Algorithm FindMinimum

var temperatures = [22, 18, 25, 15, 30, 27]

var min = temperatures[0]

For i = 1 To Size(temperatures) - 1
    If temperatures[i] < min Then
        min = temperatures[i]
    Endif
Endfor

Print "Minimum temperature:", min, "°C"

Endalgorithm

3. Search for Value

Example: Linear Search
Algorithm SearchArray

var numbers = [10, 25, 33, 47, 52, 68]

var searchValue = Input "Enter value to search for:"
var found = false
var position = -1

For i = 0 To Size(numbers) - 1
    If numbers[i] == searchValue Then
        found = true
        position = i
    Endif
Endfor

If found == true Then
    Print "✅ Found", searchValue, "at index", position
Else
    Print "❌ Value not found"
Endif

Endalgorithm

4. Reverse Array

Example: Reverse Array
Algorithm ReverseArray

var original = [1, 2, 3, 4, 5]
var size = Size(original)

Print "Original array:"
For i = 0 To size - 1
    Print original[i]
Endfor

Print ""
Print "Reversed array:"
For i = size - 1 To 0 Step -1
    Print original[i]
Endfor

Endalgorithm

Real-World Examples

Student Grade Manager

Example: Grade Manager
Algorithm GradeManager

var studentCount = Input "How many students?"
var grades[studentCount]

# Input grades
Print ""
Print "Enter grades:"
For i = 0 To studentCount - 1
    grades[i] = Input "Student " + (i + 1) + ":"
Endfor

# Calculate average
var total = 0
For i = 0 To studentCount - 1
    total = total + grades[i]
Endfor
var average = total / studentCount

# Find highest and lowest
var highest = grades[0]
var lowest = grades[0]

For i = 1 To studentCount - 1
    If grades[i] > highest Then
        highest = grades[i]
    Endif
    
    If grades[i] < lowest Then
        lowest = grades[i]
    Endif
Endfor

# Display statistics
Print ""
Print "=== GRADE STATISTICS ==="
Print "Class Average:", average
Print "Highest Grade:", highest
Print "Lowest Grade:", lowest
Print "========================"

Endalgorithm

Temperature Tracker

Example: Weekly Temperature Tracker
Algorithm TemperatureTracker

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
var temps[7]

Print "=== TEMPERATURE TRACKER ==="
Print ""

# Input temperatures
For i = 0 To 6
    temps[i] = Input days[i] + " temperature (°C):"
Endfor

# Calculate weekly average
var sum = 0
For i = 0 To 6
    sum = sum + temps[i]
Endfor
var weeklyAvg = sum / 7

# Find warmest day
var warmestTemp = temps[0]
var warmestDay = 0

For i = 1 To 6
    If temps[i] > warmestTemp Then
        warmestTemp = temps[i]
        warmestDay = i
    Endif
Endfor

# Display report
Print ""
Print "=== WEEKLY REPORT ==="
Print "Average temperature:", weeklyAvg, "°C"
Print "Warmest day:", days[warmestDay]
Print "Warmest temperature:", warmestTemp, "°C"

Endalgorithm

Common Mistakes

Mistake 1: Index Out of Bounds

❌ Wrong (array has 5 elements, 0-4):

var arr[5]
Print arr[5]  # Error! Index 5 doesn't exist

✅ Correct:

var arr[5]
Print arr[4]  # Last element

Key Takeaways

  • ✅ Arrays store multiple values under one variable name
  • ✅ Array indexing starts at 0
  • ✅ Use Size() to get array length
  • ✅ Loops are perfect for processing arrays
  • ✅ Common operations: find max/min, search, reverse
  • ✅ Watch out for index out of bounds errors
  • ✅ Arrays make managing collections of data easy

💪 Practice Exercises

Try These Exercises

Exercise 1: Array Statistics
Create a program that fills an array with numbers, then calculates: sum, average, max, min, and range (max - min).
Exercise 2: Duplicate Finder
Write a program that finds and displays all duplicate values in an array.
Exercise 3: Array Sorter
Implement bubble sort to sort an array of numbers in ascending order.
Exercise 4: Shopping Cart
Create arrays for item names, prices, and quantities. Calculate the total cost of all items.
Excellent Progress!
You now understand how to work with arrays to manage collections of data! In the next lesson, we'll explore string operations to manipulate text.