Lesson 2: Data Types, Structures, Algorithms & Methodologies

Understanding How Data is Stored and Manipulated

⏱️ 90 minutes 🐍 Python πŸ“š Year 11 Foundation
πŸ“‹

What You'll Learn Today

In this lesson, we'll explore the fundamental ways computers represent and organize information. By the end, you'll understand:

  • How computers use different number systems (binary, decimal, hexadecimal)
  • The different types of data (integers, strings, booleans, etc.)
  • How data is organized into structures (arrays, records, trees, files)
  • Advanced algorithm strategies (divide and conquer, backtracking)
  • Project management methodologies (Waterfall vs Agile)
  • Design approaches and algorithm analysis techniques
1

Number Systems for Computing

Humans naturally use decimal (base-10) because we have 10 fingers. Computers use binary (base-2) because they only understand two states: ON (1) and OFF (0).

Understanding how to convert between number systems is essential for software engineering!

Binary (Base-2)

Binary uses only two digits: 0 and 1

Each position represents a power of 2:

Position Power of 2 Value
7th bit 2⁷ 128
6th bit 2⁢ 64
5th bit 2⁡ 32
4th bit 2⁴ 16
3rd bit 2Β³ 8
2nd bit 2Β² 4
1st bit 2ΒΉ 2
0th bit 2⁰ 1
πŸ”’ Example: Converting Binary to Decimal

Binary: 10110101

Calculation:

  • (1 Γ— 128) + (0 Γ— 64) + (1 Γ— 32) + (1 Γ— 16) + (0 Γ— 8) + (1 Γ— 4) + (0 Γ— 2) + (1 Γ— 1)
  • 128 + 0 + 32 + 16 + 0 + 4 + 0 + 1
  • = 181 in decimal

Hexadecimal (Base-16)

Hexadecimal uses 16 symbols: 0-9 and A-F (where A=10, B=11, C=12, D=13, E=14, F=15)

It's commonly used because it's a compact way to represent binary numbers!

Decimal Binary Hexadecimal
000000
100011
101010A
151111F
25511111111FF

Two's Complement (Representing Negative Numbers)

Computers use two's complement to represent negative integers in binary.

How it works:

  1. Write the positive number in binary
  2. Flip all the bits (0β†’1, 1β†’0)
  3. Add 1 to the result
βž– Example: Representing -5 in 8-bit Two's Complement
  1. +5 in binary: 00000101
  2. Flip all bits: 11111010
  3. Add 1: 11111011

Result: -5 = 11111011 in two's complement

Why This Matters

Understanding number systems helps you:

  • Debug low-level programming issues
  • Work with colors in web design (e.g., #FF5733 is hexadecimal)
  • Understand memory addresses and computer architecture
  • Optimize data storage and processing
2

Data Types in Programming

A data type defines what kind of value a variable can hold and what operations can be performed on it.

Think of it like containers: you wouldn't store liquid in a cardboard box - you need the right container for the right type of data!

Data Type Description Python Example Use Case
Integer Whole numbers (positive or negative) age = 17 Counting, IDs, scores
Real/Float Decimal numbers price = 19.99 Money, measurements
String Text (sequence of characters) name = "Ulrich" Names, messages
Char Single character grade = 'A' Single letters/symbols
Boolean True or False only is_student = True Yes/no decisions
Date/Time Calendar dates and times from datetime import date Scheduling, timestamps
🐍 Python Example: Working with Data Types
PYTHON
# Different data types in action
student_id = 12345          # Integer
gpa = 3.85                  # Float
student_name = "Ulrich"     # String
initial = 'U'               # Char (single character string in Python)
is_enrolled = True          # Boolean

# You can check types
print(type(student_id))     # Output: <class 'int'>
print(type(gpa))            # Output: <class 'float'>
print(type(is_enrolled))    # Output: <class 'bool'>

# Type conversion
age_string = "17"
age_number = int(age_string)  # Convert string to integer
print(age_number + 1)         # Output: 18
Key Takeaway: Type Matters!

Using the wrong data type can cause errors:

  • "5" + "3" = "53" (string concatenation)
  • 5 + 3 = 8 (integer addition)
  • Always ensure your data types match the operations you're performing!
3

Data Structures

A data structure is a way of organizing and storing multiple pieces of data so they can be accessed and modified efficiently.

Think of them as different ways to organize your physical belongings: drawers, shelves, filing cabinets, etc.

Arrays (Lists in Python)

An array is a collection of items stored in consecutive memory locations. All items are typically the same data type.

πŸ“¦ Example: Arrays in Python
PYTHON
# List (Python's version of arrays)
test_scores = [85, 92, 78, 95, 88]

# Accessing elements (zero-indexed)
print(test_scores[0])    # First element: 85
print(test_scores[3])    # Fourth element: 95

# Modifying elements
test_scores[2] = 80      # Change third score from 78 to 80

# Adding elements
test_scores.append(90)   # Add to end: [85, 92, 80, 95, 88, 90]

# Length of array
print(len(test_scores))  # Output: 6

Advantages: Fast access to any element, simple structure

Disadvantages: Fixed size in some languages, inserting/deleting can be slow

Records (Dictionaries in Python)

A record groups together related data fields of different types. Like a student record containing name (string), ID (integer), and GPA (float).

πŸ“‹ Example: Records Using Python Dictionaries
PYTHON
# Student record as a dictionary
student = {
    "name": "Ulrich",
    "id": 12345,
    "gpa": 3.85,
    "enrolled": True,
    "subjects": ["Software Engineering", "Mathematics", "English"]
}

# Accessing fields
print(student["name"])        # Output: Ulrich
print(student["subjects"][0]) # Output: Software Engineering

# Adding new field
student["graduation_year"] = 2025

# Modifying field
student["gpa"] = 3.90

Trees

A tree is a hierarchical structure with a root node and child nodes branching out.

Real-world examples:

  • File systems (folders containing subfolders)
  • Family trees
  • Organization charts
  • HTML DOM (Document Object Model)
Binary tree diagram showing root node with two children, each having their own children. Nodes labeled with values: 50 (root), 30 (left), 70 (right), 20, 40, 60, 80 as leaves

Key terminology:

  • Root: Top node with no parent
  • Parent: Node with children below it
  • Child: Node with a parent above it
  • Leaf: Node with no children
  • Height: Number of levels in the tree

Sequential Files

A sequential file stores data in a linear sequence. You must read through records in order from start to finish.

Example: CSV files (Comma-Separated Values)

πŸ“„ Example: Reading a Sequential CSV File
SAMPLE CSV FILE (students.csv)
Name,ID,GPA
Ulrich,12345,3.85
Sarah,12346,3.92
James,12347,3.78
PYTHON
import csv

# Reading sequential file
with open('students.csv', 'r') as file:
    csv_reader = csv.reader(file)

    # Skip header row
    next(csv_reader)

    # Read each record in sequence
    for row in csv_reader:
        name, id, gpa = row
        print(f"Student: {name}, ID: {id}, GPA: {gpa}")

Advantages: Simple, easy to process all records

Disadvantages: Slow to find specific records (must read sequentially)

Data Dictionaries

A data dictionary is documentation that describes the structure of data in a system. It defines:

  • Field names
  • Data types
  • Constraints (e.g., "must be between 0-100")
  • Descriptions of what each field represents
Field Name Data Type Length Constraints Description
StudentID Integer 5 digits Unique, Required Unique identifier for student
FirstName String Max 50 chars Required Student's first name
GPA Float - 0.0 - 4.0 Grade point average
EnrollmentDate Date - Cannot be future Date student enrolled
4

Representing Algorithms: Flowcharts & Pseudocode

Flowcharts

A flowchart is a visual diagram that shows the step-by-step flow of an algorithm using standard symbols.

Symbol Name Purpose
Oval Start/End Beginning or end of algorithm
Rectangle Process An action or operation
Diamond Decision A yes/no question or condition
Parallelogram Input/Output Getting data or displaying results
Arrow Flow Line Direction of flow
Flowchart for checking if a number is even or odd. Start β†’ Input number β†’ Decision diamond 'number % 2 == 0?' β†’ Yes path to 'Output: Even' β†’ End, No path to 'Output: Odd' β†’ End

Pseudocode

Pseudocode is a plain-language description of code that's easier to read than actual programming languages but more structured than plain English.

πŸ“ Example: Finding Maximum Value in a List
PSEUDOCODE
ALGORITHM FindMaximum
    INPUT: numbers (array of integers)
    OUTPUT: maximum value

    SET max = numbers[0]

    FOR each number in numbers DO
        IF number > max THEN
            SET max = number
        END IF
    END FOR

    RETURN max
END ALGORITHM
PYTHON IMPLEMENTATION
def find_maximum(numbers):
    max_value = numbers[0]

    for number in numbers:
        if number > max_value:
            max_value = number

    return max_value

# Test
scores = [85, 92, 78, 95, 88]
print(find_maximum(scores))  # Output: 95

Structure Charts

A structure chart shows how a program is broken down into smaller modules or functions. It shows the hierarchy and relationships between different parts of the program.

Structure chart showing 'Student Management System' at top, branching to three modules: 'Add Student', 'View Students', 'Calculate GPA'. 'Calculate GPA' further branches to 'Get Grades' and 'Compute Average'

Abstraction and Refinement Diagrams

Abstraction: Starting with a high-level description and gradually adding detail

Refinement: The process of breaking down abstract concepts into detailed steps

🎯 Example: Making Toast (Levels of Abstraction)

Level 1 (Most Abstract): Make toast

Level 2:

  • Get bread
  • Toast bread
  • Add toppings

Level 3 (Most Detailed):

  • Get bread
    • Open cupboard
    • Take bread loaf
    • Remove two slices
  • Toast bread
    • Place slices in toaster
    • Set timer to medium
    • Push down lever
    • Wait for toast to pop up
5

Advanced Algorithmic Strategies

Divide and Conquer

Divide and Conquer breaks a problem into smaller sub-problems, solves them independently, then combines the results.

Steps:

  1. Divide: Break the problem into smaller parts
  2. Conquer: Solve each part recursively
  3. Combine: Merge the solutions
πŸ”ͺ Example: Merge Sort (Classic Divide & Conquer)

Problem: Sort the list [38, 27, 43, 3, 9, 82, 10]

  1. Divide: Split into [38, 27, 43, 3] and [9, 82, 10]
  2. Keep dividing until you have individual elements
  3. Conquer: Sort the small pieces
  4. Combine: Merge sorted pieces back together
PYTHON (Simplified)
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    # DIVIDE
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])

    # COMBINE (merge sorted halves)
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0

    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

    result.extend(left[i:])
    result.extend(right[j:])
    return result

Backtracking

Backtracking tries different solutions and "backs up" when it hits a dead end. It's like solving a maze - if you hit a wall, you go back and try a different path.

Common uses:

  • Solving puzzles (Sudoku, N-Queens problem)
  • Finding paths in a maze
  • Generating all possible combinations
🎯 Example: Finding All Subsets

Problem: Find all possible subsets of [1, 2, 3]

PYTHON
def find_subsets(nums):
    result = []

    def backtrack(start, current_subset):
        # Add current subset to results
        result.append(current_subset[:])

        # Try adding each remaining number
        for i in range(start, len(nums)):
            current_subset.append(nums[i])  # Choose
            backtrack(i + 1, current_subset)  # Explore
            current_subset.pop()  # Backtrack (undo choice)

    backtrack(0, [])
    return result

# Test
print(find_subsets([1, 2, 3]))
# Output: [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]]
Key Differences
  • Divide & Conquer: Breaks problem into independent parts, solves each once
  • Backtracking: Explores possibilities step-by-step, undoing wrong choices
6

Design Approaches: Top-Down vs Bottom-Up

Two Ways to Design Software

πŸ”½ Top-Down Design

Start with the big picture, then break it down

  • Begin with main problem
  • Divide into sub-problems
  • Keep dividing until simple
  • Like creating an outline first

Example: Design a calculator

  1. Main program
  2. β†’ Get inputs
  3. β†’ Perform calculation
  4. β†’ Display result

πŸ”Ό Bottom-Up Design

Build small components first, then combine

  • Start with basic functions
  • Test each component
  • Combine into larger system
  • Like building with Lego blocks

Example: Design a calculator

  1. Create add() function
  2. Create subtract() function
  3. Create multiply() function
  4. Combine into calculator

In practice: Most developers use a combination of both approaches!

7

Project Management Methodologies

How do teams organize software development projects? Two main approaches dominate the industry:

🌊 Waterfall vs πŸ”„ Agile

Waterfall Model

Sequential, linear approach

Phases (in strict order):

  1. Requirements gathering
  2. System design
  3. Implementation
  4. Testing
  5. Deployment
  6. Maintenance

Characteristics:

  • Each phase must complete before next begins
  • Heavy documentation
  • Clear milestones
  • Difficult to change requirements
  • Testing happens late

Best for:

  • Well-defined projects
  • Regulated industries (healthcare, aerospace)
  • Fixed-price contracts
  • Projects with stable requirements

Pros:

  • βœ“ Clear structure and timeline
  • βœ“ Easy to manage
  • βœ“ Well-documented
  • βœ“ Works well for small projects

Cons:

  • βœ— Inflexible to changes
  • βœ— Late testing reveals problems
  • βœ— Customer sees product late
  • βœ— High risk for complex projects

Agile Model

Iterative, flexible approach

Process (repeating cycles):

  1. Plan sprint (2-4 weeks)
  2. Design features
  3. Develop features
  4. Test continuously
  5. Review & demo
  6. Repeat with new features

Characteristics:

  • Short development cycles (sprints)
  • Continuous feedback
  • Adaptive to changes
  • Working software delivered frequently
  • Testing throughout development

Best for:

  • Evolving requirements
  • Startups and tech companies
  • Customer-facing applications
  • Complex, innovative projects

Pros:

  • βœ“ Flexible to changes
  • βœ“ Early & frequent delivery
  • βœ“ Continuous customer feedback
  • βœ“ Reduced risk

Cons:

  • βœ— Less predictable timeline
  • βœ— Requires customer involvement
  • βœ— Can lack documentation
  • βœ— Hard to estimate total cost
πŸ“± Real-World Example

Building a Social Media App:

Waterfall Approach:

  1. Spend 3 months gathering all requirements
  2. Spend 4 months designing entire system
  3. Spend 8 months coding everything
  4. Spend 2 months testing
  5. Launch complete app after 17 months
  6. Risk: Users might not like what you built!

Agile Approach:

  1. Sprint 1 (2 weeks): User registration & login β†’ Test with users
  2. Sprint 2: Profile pages β†’ Get feedback
  3. Sprint 3: Photo posting β†’ Adjust based on feedback
  4. Sprint 4: Commenting feature β†’ Continue improving
  5. Launch early version after 8 weeks, keep adding features
  6. Benefit: Users guide development!
HSC Exam Tip

Be able to explain when to use each methodology and compare their advantages/disadvantages. This is a common exam question!

8

Algorithm Analysis & Testing

Analyzing Algorithms

When evaluating an algorithm, consider:

  • Inputs: What data does it need?
  • Outputs: What does it produce?
  • Purpose: What problem does it solve?
  • Efficiency: How fast does it run?
  • Correctness: Does it always work?
πŸ” Example: Analyzing a Search Algorithm
PYTHON
def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

Analysis:

  • Input: Array (arr) and target value
  • Output: Index of target, or -1 if not found
  • Purpose: Find position of a value in an array
  • Best case: Target is first element (1 comparison)
  • Worst case: Target is last or not present (n comparisons)
  • Efficiency: O(n) - linear time

Desk Checking

Desk checking is manually tracing through code with sample data to verify correctness before running it.

Steps:

  1. Create a table with columns for each variable
  2. Walk through each line of code
  3. Update variable values as they change
  4. Check if output matches expectations
πŸ“Š Example: Desk Checking a Loop
CODE TO CHECK
total = 0
for i in range(1, 4):
    total = total + i
print(total)
Line i total Note
1-0Initialize total
210First iteration
311total = 0 + 1
221Second iteration
323total = 1 + 2
233Third iteration
336total = 3 + 3
4-6Output: 6

Peer Checking

Peer checking (also called code review) is when another programmer reviews your code to find errors and suggest improvements.

Benefits:

  • Catches errors you might miss
  • Improves code quality
  • Shares knowledge between team members
  • Ensures code follows standards
πŸŽ“

Knowledge Check

Test Your Understanding
Question 1: Convert binary 11010 to decimal.
Answer:

(1Γ—16) + (1Γ—8) + (0Γ—4) + (1Γ—2) + (0Γ—1) = 16 + 8 + 2 = 26

Question 2: What data type would you use to store a person's age?
Answer:

Integer - Age is a whole number without decimals.

Question 3: What's the difference between an array and a record?
Answer:
  • Array: Collection of items of the same type, accessed by index
  • Record: Collection of related fields of different types, accessed by field name
Question 4: When should you use Waterfall methodology instead of Agile?
Answer:

Use Waterfall when:

  • Requirements are well-defined and unlikely to change
  • Project is small and straightforward
  • Heavy documentation is required (e.g., regulated industries)
  • You have a fixed-price contract
Question 5: What is the purpose of desk checking?
Answer:

Desk checking manually traces through code with sample data to verify it works correctly before running it. It helps catch logic errors early.

πŸ’ͺ

Practice Exercises

🎯 Exercise 1: Number System Conversions

Complete these conversions:

  1. Convert decimal 45 to binary
  2. Convert binary 1101101 to decimal
  3. Convert hexadecimal 2F to decimal
  4. Represent -8 in 8-bit two's complement
🎯 Exercise 2: Design a Student Record System

Create a data dictionary for a student management system with these requirements:

  • Student ID (unique, 6 digits)
  • Full name (required, max 100 characters)
  • Date of birth (must be in the past)
  • GPA (between 0.0 and 4.0)
  • Enrollment status (active or inactive)

Then: Write Python code to create a dictionary representing one student record

🎯 Exercise 3: Draw a Flowchart

Create a flowchart for this algorithm:

"Ask the user for a password. If the password is 'secret123', display 'Access granted'. Otherwise, give them 2 more tries. After 3 failed attempts, display 'Account locked'."

🎯 Exercise 4: Desk Check This Code
PYTHON
count = 0
for num in [2, 4, 6, 8, 10]:
    if num > 5:
        count = count + 1
print(count)

Create a desk checking table showing the values of num and count after each iteration.

πŸ“‹

Lesson Summary

What We Covered Today

1. Number Systems:

  • Binary (base-2), Decimal (base-10), Hexadecimal (base-16)
  • Two's complement for negative numbers
  • Conversions between number systems

2. Data Types:

  • Integer, Float, String, Char, Boolean, Date/Time
  • Choosing appropriate types for different data
  • Type conversion in Python

3. Data Structures:

  • Arrays/Lists: Ordered collections
  • Records/Dictionaries: Related fields
  • Trees: Hierarchical structures
  • Sequential Files: Linear data storage
  • Data Dictionaries: System documentation

4. Algorithm Representation:

  • Flowcharts: Visual diagrams
  • Pseudocode: Plain-language algorithms
  • Structure Charts: Program organization
  • Abstraction & Refinement: Design process

5. Advanced Strategies:

  • Divide and Conquer: Break into parts, solve, combine
  • Backtracking: Try solutions, undo if wrong

6. Design Approaches:

  • Top-Down: Start big, break down
  • Bottom-Up: Build small, combine up

7. Project Management:

  • Waterfall: Sequential, rigid, documentation-heavy
  • Agile: Iterative, flexible, feedback-driven

8. Algorithm Analysis:

  • Inputs, Outputs, Purpose, Efficiency
  • Desk Checking: Manual verification
  • Peer Checking: Code review
πŸ“š

Homework & Next Steps

Before Next Lesson
  1. Complete all practice exercises from this lesson
  2. Practice number conversions: Do 10 binary→decimal and 5 decimal→binary conversions
  3. Create a flowchart for a real-world process (e.g., making a sandwich, doing homework)
  4. Research: Find a real company that uses Agile methodology. What benefits did they get?
  5. Code challenge: Write a Python program that stores information about 3 students using dictionaries, then prints a report

Next Lesson Preview: We'll dive into Object-Oriented Programming (OOP) fundamentals - classes, objects, inheritance, polymorphism, and encapsulation!

← Back to Ulrich's Home