IT231 Foundation of Information Technology

Foundation of Information TechnologyUnit 310 min read

Programming Fundamentals and Basic Data Structures – Variables, Control, Functions, Arrays, Stacks & Queues

Unit 3 of Foundation of Information Technology introduces programming concepts, control structures, functions, and elementary data structures, explaining how they work, showing code traces, and linking theory to everyday IT applications.

Key points

  • Understand the syntax and purpose of variables, data types, and operators in a high‑level language.
  • Design algorithms using flowcharts, pseudocode and implement them with conditional and looping statements.
  • Write reusable functions and recognise parameter passing mechanisms.
  • Model collections of data with arrays, stacks and queues, and choose the appropriate structure for a given problem.
  • Apply programming fundamentals to real‑world scenarios such as e‑payment processing, online shopping carts and network packet buffering.

1. What is Programming?

Programming is the process of giving a computer a precise set of instructions (an algorithm) that it can execute to solve a problem. A program is a text file written in a high‑level language (e.g., Python, Java, C) that is later translated into machine code.

Key Elements

Element Definition Example (Python)
Variable A named storage location that holds a value which may change during execution. count = 0
Data Type The kind of value a variable can hold (integer, float, string, boolean, etc.). price = 12.99 (float)
Operator Symbol that performs an operation on operands (arithmetic, relational, logical). total = price * qty
Statement A single line of code that performs an action. print(total)
Expression Combination of variables, operators, and literals that yields a value. price * qty + tax

IMAGE: computer keyboard labelled diagram | Standard QWERTY keyboard showing key symbols used in coding

IMAGE: monitor labelled diagram | Desktop monitor displaying a code editor window

2. Algorithms, Flowcharts & Pseudocode

An algorithm is a step‑by‑step recipe for solving a problem. To communicate algorithms clearly, we use flowcharts (graphical) and pseudocode (structured English).

Example: Find the Largest Number in a List

Pseudocode

SET max ← first element of list
FOR each element x in list starting from second
    IF x > max THEN
        SET max ← x
    END IF
END FOR
OUTPUT max

Flowchart

flowchart TD
    A["Start"] --> B["Initialize max = first element"]
    B --> C["Read next element x"]
    C --> D{"x > max?"}
    D -- Yes --> E["max = x"]
    D -- No --> F["Do nothing"]
    E --> G["Continue"]
    F --> G
    G --> H{"More elements?"}
    H -- Yes --> C
    H -- No --> I["Display max"]
    I --> J["End"]

The flowchart visualises the decision (diamond) and loop (arrow back to read next element).

3. Control Structures

Control structures dictate the order in which statements are executed.

3.1 Conditional Statements

  • if – executes a block when a condition is true.
  • if‑else – provides an alternative block when the condition is false.
  • nested if – multiple levels of decision.

Worked Example (Python)

score = 78
if score >= 80:
    grade = 'A'
elif score >= 70:
    grade = 'B'
else:
    grade = 'C'
print("Grade:", grade)

Trace: score is 78 → first condition false, second true → grade becomes 'B'.

3.2 Looping Statements

  • for – iterates over a known range or collection.
  • while – repeats while a condition remains true.

Worked Example: Sum of first N natural numbers

N = 5
total = 0
i = 1
while i <= N:
    total = total + i
    i = i + 1
print(total)

Trace:

i total after iteration
1 1
2 3
3 6
4 10
5 15

Output = 15.

4. Functions

A function groups reusable statements under a name, optionally receiving parameters and returning a value.

4.1 Definition Syntax (Python)

def function_name(parameter1, parameter2):
    # body
    result = parameter1 + parameter2
    return result

4.2 Parameter Passing

Method Description Example
Pass‑by‑value A copy of the argument is passed; changes inside the function do not affect the original variable. Primitive types in Python behave like pass‑by‑value.
Pass‑by‑reference The function receives a reference to the original object; modifications affect the caller. Mutable objects (lists, dictionaries) in Python.

4.3 Recursion

A function that calls itself. Useful for problems that can be broken into identical sub‑problems (e.g., factorial, Fibonacci).

Recursive factorial

def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)

5. Basic Data Structures

Data structures organise data for efficient access and modification.

5.1 Arrays

An array is a contiguous block of memory holding elements of the same data type, indexed from 0 (or 1 in some languages).

Memory Layout Diagram

flowchart LR
    subgraph Array["Array A[5]"]
        A0["A[0]"] --> A1["A[1]"]
        A1 --> A2["A[2]"]
        A2 --> A3["A[3]"]
        A3 --> A4["A[4]"]
    end

Operations

Operation Time Complexity
Access by index O(1)
Search (unsorted) O(n)
Insert at end O(1) amortised
Insert at middle O(n)

5.2 Stacks

A stack follows LIFO (Last‑In‑First‑Out). Primary operations: push, pop, peek.

Real‑world Analogy: A stack of plates – the last plate placed on top is the first removed.

Comparison Table: Stack vs Queue

Feature Stack (LIFO) Queue (FIFO)
Insertion point Top Rear
Deletion point Top Front
Typical use Function call management, undo feature Print spooling, CPU scheduling
Example API push(item), pop() enqueue(item), dequeue()

5.3 Queues

A queue follows FIFO (First‑In‑First‑Out). Primary operations: enqueue, dequeue, front.

Queue Diagram

flowchart LR
    subgraph Queue["Queue"]
        Front["Front"] --> A["Item1"]
        A --> B["Item2"]
        B --> Rear["Rear"]
    end

5.4 Choosing the Right Structure

Problem Preferred Structure Reason
Browser back‑button history Stack Need to return to most recent page first
Customer service ticket line Queue Serve customers in order of arrival
Storing monthly sales figures Array Fixed size, random access for reporting
Expression evaluation (post‑fix) Stack Operators applied to most recent operands

6. Integrated Example: Order Processing in an Online Shop

Consider a simplified order‑processing module for Daraz.

  1. Array order_items[ ] stores product IDs (fixed maximum of 20 items).
  2. Stack undo_stack records each action (add/remove) to enable “undo” for the user.
  3. Queue order_queue holds pending orders awaiting payment verification.

Pseudo‑code

DEFINE order_items[20]
DEFINE undo_stack as empty stack
DEFINE order_queue as empty queue

FUNCTION addItem(productID):
    FOR i FROM 0 TO 19
        IF order_items[i] = NULL THEN
            order_items[i] = productID
            push(undo_stack, ("add", i))
            RETURN
        END IF
    END FOR
    PRINT "Cart full"

FUNCTION removeItem(index):
    IF order_items[index] ≠ NULL THEN
        push(undo_stack, ("remove", index, order_items[index]))
        order_items[index] = NULL
    END IF

FUNCTION undo():
    IF NOT empty(undo_stack) THEN
        action = pop(undo_stack)
        IF action.type = "add" THEN
            order_items[action.index] = NULL
        ELSE IF action.type = "remove" THEN
            order_items[action.index] = action.value
        END IF
    END IF

FUNCTION submitOrder():
    enqueue(order_queue, copy_of(order_items))
    CLEAR order_items

The flow demonstrates how three data structures cooperate in a real e‑commerce scenario.

7. In the real world

  • eSewa uses queues to buffer incoming payment requests before they are sent to the bank’s settlement system, ensuring FIFO processing and preventing overload.
  • Daraz implements a stack for the “undo” feature in the shopping cart, allowing users to revert the most recent add/remove action instantly.
  • Google Chrome employs an array to store the list of open tabs; each tab is accessed by its index for fast switching.

Worked Real‑World Example

A Nepali bank calculates monthly loan interest using a for loop similar to the earlier sum example:

principal = 500000   # NPR
rate = 0.12          # 12% annual
months = 12
interest = 0
for m in range(1, months+1):
    interest += principal * (rate/12)
print("Total interest:", interest)

Result: NPR 60,000 interest for one year, matching the bank’s published schedule.

8. Advantages, Disadvantages & Applications

Concept Advantages Disadvantages Typical Applications
Functions Promote code reuse, simplify debugging, enable modular design Over‑abstraction can obscure flow; excessive recursion may cause stack overflow Libraries, APIs, GUI callbacks
Arrays Constant‑time index access, memory locality Fixed size, costly insert/delete in middle Image pixel buffers, lookup tables
Stacks Simple implementation, useful for backtracking Limited to LIFO, can overflow if not sized properly Expression evaluation, call stack
Queues Fair ordering, easy to implement with circular buffers May require resizing, can cause latency if processing slow Print spooling, network packet scheduling

9. Summary

Programming fundamentals provide the building blocks for any software system. Mastery of variables, control structures, functions, and elementary data structures equips students to design clear algorithms, write maintainable code, and choose the right structure for performance‑critical tasks. Real‑world platforms in Nepal and globally rely on these concepts every day, from payment gateways to online marketplaces.

Exam tip

  • Remember the syntax‑semantics link: the exam often asks you to write a short program and then predict its output. Trace the code line‑by‑line, updating variable values in a table.
  • Flowchart ↔ Pseudocode conversion: practice converting a given flowchart into pseudocode and vice‑versa; the marks are awarded for correct decision symbols and loop back‑arrows.
  • Data‑structure selection: memorize the comparison table (Stack vs Queue vs Array) and be ready to justify the choice for a scenario described in the question.
  • Function concepts: be clear on the difference between pass‑by‑value and pass‑by‑reference; a typical MCQ will present a function that modifies a list and ask for the final state of the original list.

Focus on writing clean, indented code snippets in the answer sheet; examiners reward readability as much as correctness.

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

Discussion

Loading…