General Beginner

Data Structures: Organizing Information

CodingerWeb
CodingerWeb
14 views 40 min read

Data Structures: The Containers of Programming

Data structures are ways to organize and store data so your programs can work with information efficiently. Think of them as different types of containers for different purposes.

Why Do We Need Data Structures?

Just like you organize items in your home differently (clothes in closets, books on shelves, dishes in cabinets), programs need different ways to organize data based on how it will be used.

Common Data Structures

1. Arrays/Lists - The Shopping List

Arrays store multiple items in order, like a shopping list.

Array Examples

// Creating arrays
    fruits = ["apple", "banana", "orange", "grape"]
    numbers = [1, 2, 3, 4, 5]
    temperatures = [72.5, 68.2, 75.1, 69.8]
    
    // Accessing items (usually starts at 0)
    firstFruit = fruits[0]     // "apple"
    secondFruit = fruits[1]    // "banana"
    
    // Adding items
    fruits.add("strawberry")   // Now: ["apple", "banana", "orange", "grape", "strawberry"]
    
    // Getting the size
    count = fruits.length      // 5

2. Objects/Dictionaries - The Address Book

Objects store information using key-value pairs, like an address book where you look up information by name.

Object Examples

// Creating an object
    person = {
        "name": "Alice Johnson",
        "age": 28,
        "city": "New York",
        "email": "alice@email.com"
    }
    
    // Accessing values
    personName = person["name"]        // "Alice Johnson"
    personAge = person["age"]          // 28
    
    // Adding new information
    person["phone"] = "555-1234"
    
    // Updating existing information
    person["age"] = 29

3. Stacks - The Plate Stack

Stacks work like a stack of plates - you can only add or remove from the top (Last In, First Out - LIFO).

Stack Example

stack = []
    
    // Push (add to top)
    stack.push("first")
    stack.push("second")
    stack.push("third")
    // Stack now: ["first", "second", "third"]
    
    // Pop (remove from top)
    item = stack.pop()    // Returns "third"
    // Stack now: ["first", "second"]

4. Queues - The Line at the Store

Queues work like a line at the store - first person in line is first to be served (First In, First Out - FIFO).

Queue Example

queue = []
    
    // Enqueue (add to back)
    queue.enqueue("Alice")
    queue.enqueue("Bob")
    queue.enqueue("Charlie")
    // Queue: ["Alice", "Bob", "Charlie"]
    
    // Dequeue (remove from front)
    served = queue.dequeue()    // Returns "Alice"
    // Queue now: ["Bob", "Charlie"]

Choosing the Right Data Structure

Use Case Best Data Structure Why
Store student grades Array Simple list of numbers
Store student information Object Multiple related properties
Undo feature in text editor Stack Last action should be undone first
Print queue Queue First document sent should print first

Real-World Examples

Student Management System

// Array of student objects
    students = [
        {
            "id": 1,
            "name": "Alice",
            "grades": [85, 92, 78, 96],
            "email": "alice@school.edu"
        },
        {
            "id": 2,
            "name": "Bob",
            "grades": [79, 85, 88, 82],
            "email": "bob@school.edu"
        }
    ]
    
    // Function to calculate average grade
    function calculateAverage(grades):
        total = 0
        for each grade in grades:
            total = total + grade
        return total / length(grades)
    
    // Process each student
    for each student in students:
        average = calculateAverage(student["grades"])
        print(student["name"] + " average: " + average)

Shopping Cart System

// Shopping cart using array of objects
    cart = [
        {"item": "laptop", "price": 999.99, "quantity": 1},
        {"item": "mouse", "price": 25.99, "quantity": 2},
        {"item": "keyboard", "price": 79.99, "quantity": 1}
    ]
    
    // Calculate total
    function calculateTotal(cart):
        total = 0
        for each item in cart:
            itemTotal = item["price"] * item["quantity"]
            total = total + itemTotal
        return total
    
    total = calculateTotal(cart)
    print("Cart total: $" + total)

Common Operations

Array Operations

  • Access: Get item by position
  • Search: Find item in the array
  • Insert: Add item at specific position
  • Delete: Remove item from array
  • Sort: Arrange items in order

Object Operations

  • Get: Retrieve value by key
  • Set: Add or update key-value pair
  • Delete: Remove key-value pair
  • Keys: Get all keys
  • Values: Get all values

🎯 Data Structure Practice

  1. Create an array of your favorite movies and print each one
  2. Build an object representing a book with title, author, pages, and year
  3. Design a simple to-do list using an array
  4. Create a contact list using an array of person objects

Performance Considerations

Different data structures have different strengths:

  • Arrays: Fast access by index, slower for searching
  • Objects: Fast lookup by key, good for related data
  • Stacks: Very fast add/remove from top
  • Queues: Fair processing order, good for task management

Next Steps

As you advance, you'll learn about more complex data structures like:

  • Trees (for hierarchical data)
  • Graphs (for network-like relationships)
  • Hash tables (for very fast lookups)
  • Linked lists (for dynamic sizing)