IT231 Foundation Of Information Technology

Foundation Of Information TechnologyUnit 39 min read

Programming Fundamentals & Data Structures: Variables, Algorithms, Arrays, Linked Lists, Stacks, Queues, Trees

Unit 3 of Foundation Of Information Technology: This note demystifies programming logic (variables, loops, functions) and core data structures (arrays, linked lists, stacks, queues, trees) with definitions, step-by-step examples, comparisons, and real-world ties to apps like eSewa, Daraz, and Pathao—plus exam-ready dia

TAKEAWAYS:

  • Learn how variables, loops, and functions form the building blocks of any program, from eSewa’s transaction checks to Daraz’s order processing.
  • Master arrays and linked lists to model real-world collections like Pathao’s driver assignments or NTC’s call queues.
  • Understand stacks (undo/redo in apps) and queues (Ncell’s call handling) with push/pop and enqueue/dequeue operations.
  • See how binary trees (used in NEPSE’s stock searches) and hash tables (eSewa’s user authentication) organize data efficiently.
  • Compare data structures by time/space trade-offs in a table, and trace algorithms step-by-step like a debugger.
  • Write clean code with pseudocode and flowcharts, avoiding common pitfalls seen in exam questions.

1. Introduction to Programming Fundamentals

Programming is the process of writing instructions (code) for a computer to perform tasks. It relies on variables, data types, control structures (loops/conditionals), and functions to solve problems systematically.

1.1 Variables and Data Types

Variables store data temporarily in memory. They have:

  • A name (e.g., userBalance, orderID)
  • A data type (e.g., integer, string, boolean)
  • A value (e.g., 500, "Nepal", True)
flowchart TD
    A["Variable"] --> B["Name (e.g., salary)"]
    A --> C["Data Type (int, str, bool)"]
    A --> D["Value (e.g., 3000)"]

Example: eSewa Transaction Check

balance = 1000  # int
transaction = "success"  # str
isActive = True  # bool

Why? eSewa uses variables to track user balances (balance), transaction status (transaction), and account status (isActive).


1.2 Control Structures

Loops repeat actions until a condition is met. Common types:

  • For loop: Iterates a fixed number of times (e.g., processing 10 orders in Daraz).
  • While loop: Runs while a condition is true (e.g., checking NTC’s network until a call connects).
flowchart TD
    A["For Loop"] --> B["Loop variable (i=0 to n-1)"]
    A --> C["Body (e.g., print(order))"]
    D["While Loop"] --> E["Condition (e.g., isConnected == False)"]
    D --> F["Body (e.g., retryConnection())"]
    G["Loop Control"] -->|"Initialization"| B
    G -->|"Condition Check"| E
    G -->|"Update"| A

Example: Daraz Order Processing

for order in orders:  # For loop
    if order.status == "pending":
        ship(order)  # Process each pending order

1.3 Functions

Functions group reusable code (e.g., calculating loan interest in banks, validating user input in eSewa).

flowchart TD
    A["Function Definition"] --> B["def calculateInterest(principal, rate):"]
    B --> C["    return principal * rate / 100"]
    D["Function Call"] --> E["interest = calculateInterest(10000, 5)"]

Example: NEPSE Stock Price Update

def update_price(stock, new_price):
    if new_price > stock.last_price * 1.1:  # 10% increase
        stock.last_price = new_price
        print(f"{stock.name} updated to {new_price}")

2. Data Structures

Data structures organize data for efficient access and manipulation. Key types:

037.575112.5150Arrays100Linked Lists120Stacks80Queues90Trees150
Comparison of time complexity for insertion and deletion operations in different data structures.

2.1 Arrays

Arrays store multiple values of the same type in contiguous memory. Used in:

  • Pathao’s driver assignments (array of drivers).
  • Ncell’s call logs (array of call records).
flowchart TD
    A["Array"] --> B["Indexed (0-based)"]
    B --> C["Example: drivers[0] = 'Rahul'"]
    B --> D["drivers[1] = 'Sita'"]
    B --> E["drivers[2] = 'Arjun'"]
    F["Memory Layout"] -->|"Contiguous"| B

Example: NTC Call Queue

callQueue = ["9841234567", "9812345678", "9876543210"]  # Array of callers
for caller in callQueue:
    print(f"Connecting to {caller}")

2.2 Linked Lists

Linked lists store data in nodes, where each node points to the next. Used in:

  • Daraz’s order history (linked list of past orders).
  • Pathao’s ride requests (linked list of pending rides).
Node 3 (Driver ID: 103)Node 2 (Driver ID: 102)Node 1 (Driver ID: 101)
Linked list structure showing node connections and data storage.

Example: Pathao Ride Requests

class RideNode:
    def __init__(self, driver_id):
        self.driver_id = driver_id
        self.next = None

# Linked list of pending rides
ride1 = RideNode("101")
ride2 = RideNode("102")
ride1.next = ride2

2.3 Stacks (LIFO)

Stacks follow Last-In-First-Out (LIFO). Used in:

  • eSewa’s undo/redo functionality.
  • Browser history (back button).
flowchart TD
    A["Push"] --> B["Add to top"]
    C["Pop"] --> D["Remove from top"]
    E["Stack"] -->|"Top"| F["Order 3"]
    E -->|"Below"| G["Order 2"]
    E -->|"Bottom"| H["Order 1"]

Example: eSewa Transaction History

transactions = []  # Stack
transactions.append("Transfer to Friend")  # Push
transactions.append("Bill Payment")        # Push
print(transactions.pop())  # Pop: "Bill Payment" (last action)

2.4 Queues (FIFO)

Queues follow First-In-First-Out (FIFO). Used in:

  • Ncell’s call center queue.
  • Printer job scheduling.
flowchart TD
    A["Enqueue"] --> B["Add to rear"]
    C["Dequeue"] --> D["Remove from front"]
    E["Queue"] -->|"Front"| F["Call 1"]
    E -->|"Rear"| G["Call 2"]

Example: Ncell Call Handling

from collections import deque
call_queue = deque()
call_queue.append("9841234567")  # Enqueue
call_queue.append("9812345678")  # Enqueue
print(call_queue.popleft())  # Dequeue: "9841234567" (first caller)

2.5 Trees (Binary Trees)

Trees organize hierarchical data. Used in:

  • NEPSE’s stock search (binary tree for fast lookup).
  • File systems (folders/subfolders).
Sub-Stock 1Sub-Stock 2Stock BRoot (Stock A)
Binary tree structure for NEPSE stock search.

Example: NEPSE Stock Search

class StockNode:
    def __init__(self, name):
        self.name = name
        self.left = None
        self.right = None

# Binary tree for stocks
root = StockNode("NEPSE")
root.left = StockNode("IPC")
root.right = StockNode("NICL")

3. Comparison of Data Structures

Structure Access Time Insertion/Deletion Use Case
Array O(1) O(n) Fixed-size collections
Linked List O(n) O(1) Dynamic-size collections
Stack O(1) (top) O(1) LIFO operations
Queue O(1) (front) O(1) FIFO operations
Binary Tree O(log n) O(log n) Hierarchical data

4. Worked Example: Daraz Order Queue

Scenario: Daraz receives 5 orders. Model the queue and simulate processing.

Enqueue Order 1Order 1 added toqueueEnqueue Order 2Order 2 added toqueueEnqueue Order 3Order 3 added toqueueEnqueue Order 4Order 4 added toqueueEnqueue Order 5Order 5 added toqueueDequeue Order 1Order 1 processedDequeue Order 2Order 2 processed
Daraz order processing queue simulation.

Python Code:

from collections import deque
orders = deque(["Order1", "Order2", "Order3", "Order4", "Order5"])

while orders:
    current_order = orders.popleft()  # Dequeue
    print(f"Processing {current_order}")

Output:

Processing Order1
Processing Order2
Processing Order3
Processing Order4
Processing Order5

5. Algorithm Trace Example

Problem: Calculate the sum of even numbers in an array. Algorithm:

  1. Initialize sum = 0.
  2. Loop through array:
    • If number is even, add to sum.
  3. Return sum.

Trace Table:

Index (i) Array Value Even Check Sum
0 2 True 0 + 2 = 2
1 3 False 2
2 4 True 2 + 4 = 6

Example Array: [2, 3, 4, 5, 6] Final Sum: 6 (2 + 4).


In the Real World

  1. eSewa’s Transaction Stack:

    • Idea: Uses a stack to track transaction history (undo/redo).
    • How: Each transaction is pushed onto the stack. When a user undoes, the top transaction is popped and reversed (e.g., a transfer becomes a refund).
  2. Daraz’s Order Queue:

    • Idea: Uses a queue to process orders in arrival order (FIFO).
    • How: New orders are enqueued. The system dequeues and processes the oldest order first, ensuring fairness.
  3. NEPSE’s Stock Search Tree:

    • Idea: Uses a binary search tree for efficient stock lookup.
    • How: Stocks are inserted into the tree. Searching for "IPC" takes O(log n) time, faster than a linear search in an array.

Exam Tip

  • Definitions: Always define terms like data structure, algorithm, LIFO/FIFO clearly.
  • Diagrams: Draw flowcharts for loops/functions and labeled diagrams for stacks/queues.
  • Traces: Show step-by-step execution tables (like the Daraz queue example).
  • Comparisons: Use tables to compare data structures (e.g., access time vs. insertion time).
  • Real-World Links: Tie examples to apps (eSewa, Daraz) or systems (NTC, NEPSE) to score extra marks.
  • Pseudocode: Write clean pseudocode for algorithms (e.g., "START → Initialize sum → FOR each number → IF even → sum = sum + number → ENDFOR → END").

Based on the TU BITM syllabus for Foundation Of Information Technology (IT231), unit 3.

Discussion

Loading…