BeginnerProgramming Fundamentals6-8 weeks

Introduction to Programming (The Basics)

Master the fundamental concepts of programming including variables, data types, control structures, loops, arrays, functions, and object-oriented programming basics.

Instructor: julekgwa
Published: 8/3/2025
Free

Introduction to Programming (The Basics)

Welcome to the comprehensive Introduction to Programming course! This course is designed for complete beginners who want to learn the fundamental concepts of programming. No prior experience is required.

What You'll Learn

By the end of this course, you will understand:

  • General Concepts: Data hierarchy, variables, constants, and arithmetic operations
  • Problem Solving: How to analyze problems and create algorithms
  • Selection Control Structure: Decision-making with if statements and case structures
  • Loops: Repetitive execution and iteration
  • Arrays: Working with collections of data
  • Functions: Creating reusable code blocks
  • Working With Files: File input/output operations
  • Introduction to Object-oriented Programming: Basic OOP concepts

Course Structure

This course is organized into 8 comprehensive modules, each building upon the previous concepts to give you a solid foundation in programming.


Module 1: General Concepts

1.1 Data Hierarchy

Data hierarchy refers to the systematic organization of data, often in a hierarchical form.

Data Organization Involves:

  • Character
  • Field
  • Record
  • File
  • Table
  • Database
  • Data Warehouse

1.2 Variables

Variables are containers for storing data values.

For Example:

x = 3
y = 6

x stores the value 3 and y stores the value 6

Naming Variables: Rules and Best Practices

  • All variable names must begin with a letter, underscore, or a dollar sign
  • The variable name must be unique
  • The variable name must be descriptive and should be short as possible
  • The variable name cannot contain spaces
  • The variable name can contain letters and numbers

Naming Conventions

The convention is to use only lower-case letters in the name of a variable, except where two or more words are joined. In such cases, we use camel casing or underscore to properly write our variable.

For Example:

  • name
  • address

Joining two or more words:

  • Method 1: Camel Casing - studentName
  • Method 2: Underscore - student_name

Types of Variables (Datatypes)

  • Numeric - Numbers (integers, decimals)
  • Character - Single characters
  • String - Text/sequences of characters
  • Boolean - True/False values

Assigning Values to Variables

You can assign a value to a variable when you define/create the variable:

studentName = "John";

Or you can assign the value to a variable after defining it:

studentName; // Creating a variable without assigning a value
studentName = "Peter"; // Later assigning a value

1.3 Constants

A constant is a variable whose value cannot be changed once it has been assigned a value.

Constant Naming Conventions

In some programming languages, constants are named using all uppercase.

For example:

HOURLY_RATE = 8.50

1.4 Using Variables

The assignment symbol (=) is used to assign a value to a variable.

For example:

variableName = value

1.5 Arithmetic Expressions

An arithmetic expression is an expression that results in a numeric value.

Arithmetic Operators

OperatorDescriptionExampleResultsPrecedence
^Exponent2 ^ 4161
-Negation-True, --6False, +62
*, /Multiplication and Division5 * 7, 72/835, 93
\Integer division37\574
modModulus37 mod 525
+, -Addition and subtraction4 + 7, 14 - 511, 96

How Expressions Are Executed

  1. From left to right
  2. The operator with the highest order of precedence is done before others
  3. Parenthesis (or brackets) are used to change the order of execution

Example:

5 - 3 ^ 2 \ 8 + 17 mod 3 * 2
= 5 - 9 \ 8 + 17 mod 3 * 2    (3 ^ 2 = 9 first)
= 5 - 9 \ 8 + 17 mod 6        (3 * 2 = 6)
= 5 - 1 + 17 mod 6            (9 \ 8 = 1)
= 5 - 1 + 5                   (17 mod 6 = 5)
= 4 + 5                       (5 - 1 = 4)
= 9

Module 2: Problem Solving and Understanding the Problem

2.1 Problem Solving

Before you can solve a problem, it's essential to understand what the problem is!

Steps to follow to ensure you understand a problem:

  1. Read the problem carefully
  2. Understand what the problem entails
  3. Only then write down the steps to solve the problem

2.2 Understanding the Problem

When you are faced with a problem to solve, the problem is read carefully, and may be read a number of times to be very sure that the problem is understood. Deleting all unnecessary information from the problem statement can help you arrive at the crux of the problem.

Example:

The Fresh Greengrocer store sells bananas at 85 cents each, apples at 65 cents each and oranges at 90 cents. John has $15 and wants to buy 10 bananas and 5 apples. Calculate the amount due.

Solving the problem: To be able to calculate the amount due, we only need to know how many apples and bananas to buy and what their prices are. The other information is irrelevant.

The problem becomes:

The Fresh Greengrocer store sells bananas at 85 cents each, apples at 65 cents each. John wants to buy 10 bananas and 5 apples. Calculate the amount due.

2.3 Pseudocode

Pseudocode is a detailed yet readable description of what a computer program or algorithm must do. It is mostly given in simple English.

Example:

Peter sells oranges, bananas, guavas and apples. Last week he sold 50 apples, 100 bananas, 80 oranges and some guavas. This week he sold twice as many items. How many did he sell?

To solve the problem:

  1. Ask the question to obtain the number of guavas sold last week
  2. Get the number of guavas
  3. Calculate the total number by adding the four numbers to determine the total number sold last week
  4. Multiply last week's total by 2 to obtain this week's total

2.4 Writing Algorithm

An algorithm is a procedure or formula for solving a problem.

Writing algorithms in pseudocode isn't the only way to plan a computer-related solution to a problem, you can use flowcharts or Nassi Shneidermann diagrams.


Module 3: Selection Control Structure

3.1 Relational Operators

A relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. All of the relational operators result in a Boolean value (True or False).

SymbolDescription
=Equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
<>Not equal to

3.2 Logical Operators

A logical operator joins two Boolean expressions to yield a Boolean result (True or False).

SymbolDescription
NOT (!)Returns the opposite
AND (&&)Returns True if both expressions are True
OR (||)Returns True if one expression is True

3.3 Simple If Statement

If statement specify a block of code to be executed, if a specified condition is true.

For example:

if hours < 18 then
    display "Good day"
endif

3.4 Simple If-then-else Statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

For example:

if hours < 18 then
    display "Good day"
else
    display "Good evening"
endif

3.5 Compound If Statement

A compound if-statement occurs when two or more conditions must exist before you want to execute your code. Compound If statements use logical operators – And, Or, Not.

For example:

if number > 10 AND number < 20 then
    display "Number is between 10 and 20"
else
    display "Number is not between 10 and 20"
endif

3.6 Nested If Statement

A nested if statement is used if more than one decision must be made before a suitable action can be taken.

For example:

if number < 10 then
    if number > 5 then
        display "Number is between 5 and 10"
    else
        display "Number is not between 5 and 10"
    endif
else if number > 10 then
    if number < 20 then
        display "Number is between 10 and 20"
    endif
endif

3.7 The Select Case Structure

The select case statement is used to perform different actions based on different conditions.

For example:

select case hour
    case 7
        display "Good morning"
    case 12
        display "Good day"
    case 19
        display "Good evening"
endselect

Module 4: Loops

4.1 The For-next Loop

Loops can execute a block of code a number of times.

The syntax for the for-next loop:

for variable1 = begin-value to end-value [step variable2]
    code block to be executed
next variable1

4.2 Nested For Statement

For loops can be nested inside other for loops to create more complex iteration patterns.

Example 1: Multiplication Table

for i = 1 to 10
    for j = 1 to 10
        result = i * j
        display i + " x " + j + " = " + result
    next j
    display "---"  // Separator between tables
next i

Example 2: Creating a Pattern

for row = 1 to 5
    for col = 1 to row
        display "*"
    next col
    display new line
next row

This creates:

*
**
***
****
*****

Example 3: Processing a 2D Array

for row = 1 to 3
    for col = 1 to 4
        display "Position [" + row + "," + col + "]"
        // Process element at [row, col]
    next col
next row

4.3 The Do Loops

There are two types of Do loop:

  • Pre-test loop (Do-while statement)
  • Post-test loop (Do-loop-until statement)

Pre-test Loop

The condition is tested before the statements within the loop are processed.

Syntax:

do while number < 10
    code block to be executed
loop

Post-test Loop

The statements in the body of the loop are processed at least once, before checking if the condition is true, then it will repeat loop as long as the condition is true.

Syntax:

do
    code block to be executed
loop until number = 10

Module 5: Arrays

5.1 What is an Array?

An array is a collective name given to a group of similar quantities.

For example:

  • Percentage marks of 100 students
  • Number of chairs in home
  • Salaries of 300 employees
  • Ages of 25 students

5.2 Properties of an Array

  • It has a single name
  • A single variable in an array is called an element
  • All the elements in an array are the same data type
  • The position of an element in an array is called an index or a subscript

5.3 Parallel Array

Parallel array - two or more arrays that are related to one another and have the same number of elements.

Example: Student Records

// Three parallel arrays for student information
studentNames[5] = ["John", "Mary", "Bob", "Alice", "Tom"]
studentAges[5] = [20, 19, 21, 18, 22]
studentGrades[5] = [85, 92, 78, 96, 88]

// To display information for student at index 2:
display "Student: " + studentNames[2]
display "Age: " + studentAges[2]
display "Grade: " + studentGrades[2]

// Output:
// Student: Bob
// Age: 21
// Grade: 78

Example: Employee Database

employeeID[100] = [1001, 1002, 1003, ...]
employeeName[100] = ["Smith", "Johnson", "Williams", ...]
employeeSalary[100] = [50000, 45000, 55000, ...]

// Finding employee by ID
searchID = 1002
for i = 0 to 99
    if employeeID[i] = searchID then
        display "Employee: " + employeeName[i]
        display "Salary: $" + employeeSalary[i]
        break
    endif
next i

5.4 Two Dimensional Array

2D arrays are generally known as matrix. They are used to store data in a table format with rows and columns.

Example 1: Student Grades Matrix

// 2D array: 4 students x 3 subjects
grades[4][3] = [
    [85, 92, 78],  // Student 1: Math, Science, English
    [90, 88, 85],  // Student 2: Math, Science, English
    [78, 85, 92],  // Student 3: Math, Science, English
    [95, 89, 90]   // Student 4: Math, Science, English
]

// Accessing specific grade: Student 2's Science grade
display grades[1][1]  // Output: 88 (remember arrays start at 0)

// Calculate average for Student 1
total = 0
for subject = 0 to 2
    total = total + grades[0][subject]
next subject
average = total / 3
display "Student 1 average: " + average

Example 2: Tic-Tac-Toe Board

// 3x3 game board
board[3][3] = [
    ["X", "O", " "],
    [" ", "X", " "],
    ["O", " ", "X"]
]

// Display the board
for row = 0 to 2
    for col = 0 to 2
        display board[row][col] + " "
    next col
    display new line
next row

Example 3: Sales Data by Quarter

// Sales data: 4 quarters x 3 regions
sales[4][3] = [
    [1000, 1200, 900],   // Q1: North, South, East
    [1100, 1300, 950],   // Q2: North, South, East
    [1050, 1250, 980],   // Q3: North, South, East
    [1200, 1400, 1100]   // Q4: North, South, East
]

// Calculate total sales for all quarters and regions
totalSales = 0
for quarter = 0 to 3
    for region = 0 to 2
        totalSales = totalSales + sales[quarter][region]
    next region
next quarter
display "Total Sales: $" + totalSales

Module 6: Functions

6.1 Parameters

A parameter represents a value that the function expects you to pass when you call it. An argument is an expression used when calling the method.

There are two types of parameters:

  • Value parameters - pass an argument by value
  • Reference parameters - pass an argument by address not by value

Value Parameters Example

function calculateArea(length, width)
    area = length * width
    return area
endfunction

// Calling the function
roomLength = 10
roomWidth = 12
roomArea = calculateArea(roomLength, roomWidth)
display "Room area: " + roomArea + " square feet"

Reference Parameters Example

function swapValues(ref a, ref b)
    temp = a
    a = b
    b = temp
endfunction

// Before swap
x = 5
y = 10
display "Before: x=" + x + ", y=" + y  // Before: x=5, y=10

swapValues(x, y)

// After swap
display "After: x=" + x + ", y=" + y   // After: x=10, y=5

Multiple Parameters Example

function calculateGrade(homework, midterm, final)
    // Weighted calculation: homework 20%, midterm 30%, final 50%
    totalGrade = (homework * 0.2) + (midterm * 0.3) + (final * 0.5)

    if totalGrade >= 90 then
        return "A"
    else if totalGrade >= 80 then
        return "B"
    else if totalGrade >= 70 then
        return "C"
    else if totalGrade >= 60 then
        return "D"
    else
        return "F"
    endif
endfunction

// Usage
studentGrade = calculateGrade(85, 78, 92)
display "Student grade: " + studentGrade

6.2 Calling and Using Functions

The syntax for calling a function is:

functionName(argument list)

Basic Function Examples

Example 1: Simple Function with No Parameters

function greetUser()
    display "Welcome to our program!"
    display "Have a great day!"
endfunction

// Calling the function
greetUser()

Example 2: Function with Return Value

function getCircumference(radius)
    pi = 3.14159
    circumference = 2 * pi * radius
    return circumference
endfunction

// Using the function
circleRadius = 5
result = getCircumference(circleRadius)
display "Circumference: " + result

Example 3: Function with Multiple Parameters

function calculateTip(billAmount, tipPercentage)
    tipAmount = billAmount * (tipPercentage / 100)
    totalAmount = billAmount + tipAmount
    return totalAmount
endfunction

// Usage
bill = 50.00
tipPercent = 18
total = calculateTip(bill, tipPercent)
display "Total with tip: $" + total

Example 4: Function Using Arrays

function findMaxValue(numbers[], size)
    maxValue = numbers[0]
    for i = 1 to size - 1
        if numbers[i] > maxValue then
            maxValue = numbers[i]
        endif
    next i
    return maxValue
endfunction

// Usage
scores[5] = [85, 92, 78, 96, 88]
highest = findMaxValue(scores, 5)
display "Highest score: " + highest

Example 5: Recursive Function

function factorial(n)
    if n <= 1 then
        return 1
    else
        return n * factorial(n - 1)
    endif
endfunction

// Calculate 5! (5 factorial)
result = factorial(5)
display "5! = " + result  // Output: 5! = 120

Module 7: Working with Files

7.1 Open and Close a File

Learn the fundamental operations for working with files in programming, including how to properly open files for reading or writing and ensuring they are properly closed to prevent resource leaks.

Basic File Operations

Opening a File for Reading:

file studentFile
open studentFile for reading from "students.txt"

if file is open then
    display "File opened successfully"
else
    display "Error: Could not open file"
endif

Opening a File for Writing:

file outputFile
open outputFile for writing to "results.txt"

if file is open then
    display "File ready for writing"
else
    display "Error: Could not create file"
endif

Opening a File for Appending:

file logFile
open logFile for appending to "activity.log"

if file is open then
    display "Ready to append to log file"
endif

Closing Files:

// Always close files when done
close studentFile
close outputFile
close logFile
display "All files closed properly"

File Opening Modes

ModeDescriptionUsage
ReadOpen file for reading onlyViewing existing data
WriteOpen file for writing (overwrites existing)Creating new files
AppendOpen file for writing at the endAdding to existing files

7.2 Read and Write to File

Master the techniques for reading data from files and writing data to files, essential skills for data persistence and file processing.

Reading from Files

Example 1: Reading Line by Line

file inputFile
open inputFile for reading from "data.txt"

while not end of file
    read line from inputFile into currentLine
    display "Read: " + currentLine
endwhile

close inputFile

Example 2: Reading Student Records

file studentFile
open studentFile for reading from "students.txt"

studentCount = 0
while not end of file
    read line from studentFile into studentName
    read line from studentFile into studentGrade

    display "Student: " + studentName
    display "Grade: " + studentGrade
    display "---"

    studentCount = studentCount + 1
endwhile

close studentFile
display "Total students processed: " + studentCount

Example 3: Reading Numbers for Calculation

file numbersFile
open numbersFile for reading from "numbers.txt"

sum = 0
count = 0
while not end of file
    read number from numbersFile into currentNumber
    sum = sum + currentNumber
    count = count + 1
endwhile

close numbersFile

if count > 0 then
    average = sum / count
    display "Average: " + average
endif

Writing to Files

Example 1: Writing Simple Data

file outputFile
open outputFile for writing to "output.txt"

write "Program Results" to outputFile
write "===============" to outputFile
write "Date: 2025-08-03" to outputFile
write "Status: Complete" to outputFile

close outputFile
display "Data written to file successfully"

Example 2: Writing Student Report

file reportFile
open reportFile for writing to "student_report.txt"

students[3] = ["Alice", "Bob", "Charlie"]
grades[3] = [92, 85, 78]

write "Student Grade Report" to reportFile
write "===================" to reportFile

for i = 0 to 2
    write "Student: " + students[i] to reportFile
    write "Grade: " + grades[i] to reportFile

    if grades[i] >= 90 then
        write "Performance: Excellent" to reportFile
    else if grades[i] >= 80 then
        write "Performance: Good" to reportFile
    else
        write "Performance: Needs Improvement" to reportFile
    endif

    write "---" to reportFile
next i

close reportFile

Example 3: Logging Program Activity

file logFile
open logFile for appending to "program.log"

function logMessage(message)
    currentTime = getCurrentTime()
    write currentTime + ": " + message to logFile
endfunction

// Usage throughout program
logMessage("Program started")
logMessage("User logged in")
logMessage("File processed successfully")
logMessage("Program ended")

close logFile

File Processing Best Practices

Complete File Processing Example:

function processGradeFile()
    file inputFile, outputFile

    // Open input file
    open inputFile for reading from "raw_grades.txt"
    if not file is open then
        display "Error: Cannot open input file"
        return
    endif

    // Open output file
    open outputFile for writing to "processed_grades.txt"
    if not file is open then
        display "Error: Cannot create output file"
        close inputFile
        return
    endif

    // Process data
    totalStudents = 0
    totalGrades = 0

    write "Grade Processing Report" to outputFile
    write "======================" to outputFile

    while not end of file
        read line from inputFile into studentName
        read line from inputFile into grade

        totalStudents = totalStudents + 1
        totalGrades = totalGrades + grade

        // Determine letter grade
        if grade >= 90 then
            letterGrade = "A"
        else if grade >= 80 then
            letterGrade = "B"
        else if grade >= 70 then
            letterGrade = "C"
        else if grade >= 60 then
            letterGrade = "D"
        else
            letterGrade = "F"
        endif

        write studentName + ": " + grade + " (" + letterGrade + ")" to outputFile
    endwhile

    // Calculate and write summary
    if totalStudents > 0 then
        average = totalGrades / totalStudents
        write "==================" to outputFile
        write "Total Students: " + totalStudents to outputFile
        write "Class Average: " + average to outputFile
    endif

    // Close files
    close inputFile
    close outputFile

    display "Grade processing complete!"
endfunction

Module 8: Introduction to Object-oriented Programming

8.1 Objects

Objects are the fundamental building blocks of object-oriented programming. An object represents a real-world entity with properties and behaviors.

Real-world Examples of Objects:

  • Car: Properties (color, model, year), Behaviors (start, stop, accelerate)
  • Bank Account: Properties (balance, account number), Behaviors (deposit, withdraw, check balance)
  • Student: Properties (name, ID, grade), Behaviors (study, take exam, submit assignment)

Programming Example - Car Object:

object Car
    // Properties (also called attributes)
    color = "red"
    model = "Toyota"
    year = 2023
    speed = 0

    // Methods (behaviors)
    method start()
        display "Car is starting..."
        display "Engine is now running"
    endmethod

    method accelerate(amount)
        speed = speed + amount
        display "Speed is now: " + speed + " mph"
    endmethod

    method brake(amount)
        speed = speed - amount
        if speed < 0 then
            speed = 0
        endif
        display "Speed is now: " + speed + " mph"
    endmethod
endobject

8.2 Properties

Properties (also called attributes) are the characteristics or data that describe an object.

Example 1: Student Object Properties

object Student
    // Properties store the state of the object
    name = ""
    studentID = ""
    age = 0
    gpa = 0.0
    major = ""
    enrollmentYear = 0
    isActive = true

    // Method to display student information
    method displayInfo()
        display "Name: " + name
        display "ID: " + studentID
        display "Age: " + age
        display "GPA: " + gpa
        display "Major: " + major
        display "Status: " + (isActive ? "Active" : "Inactive")
    endmethod
endobject

Example 2: Bank Account Properties

object BankAccount
    // Private properties (encapsulation)
    accountNumber = ""
    balance = 0.0
    accountType = ""
    ownerName = ""
    interestRate = 0.0

    // Method to safely access balance
    method getBalance()
        return balance
    endmethod

    // Method to safely modify balance
    method setBalance(newBalance)
        if newBalance >= 0 then
            balance = newBalance
        else
            display "Error: Balance cannot be negative"
        endif
    endmethod
endobject

8.3 Methods

Methods are the functions or behaviors that an object can perform.

Example 1: Calculator Object Methods

object Calculator
    result = 0

    method add(a, b)
        result = a + b
        return result
    endmethod

    method subtract(a, b)
        result = a - b
        return result
    endmethod

    method multiply(a, b)
        result = a * b
        return result
    endmethod

    method divide(a, b)
        if b != 0 then
            result = a / b
            return result
        else
            display "Error: Division by zero"
            return 0
        endif
    endmethod

    method getLastResult()
        return result
    endmethod
endobject

// Using the calculator
myCalculator = new Calculator
sum = myCalculator.add(10, 5)
display "10 + 5 = " + sum

product = myCalculator.multiply(4, 7)
display "4 × 7 = " + product

Example 2: Library Book Methods

object LibraryBook
    title = ""
    author = ""
    isbn = ""
    isCheckedOut = false
    dueDate = ""
    borrowerName = ""

    method checkOut(borrower, returnDate)
        if not isCheckedOut then
            isCheckedOut = true
            borrowerName = borrower
            dueDate = returnDate
            display "Book checked out to: " + borrower
            display "Due date: " + returnDate
        else
            display "Book is already checked out"
        endif
    endmethod

    method returnBook()
        if isCheckedOut then
            display "Book returned by: " + borrowerName
            isCheckedOut = false
            borrowerName = ""
            dueDate = ""
        else
            display "Book was not checked out"
        endif
    endmethod

    method isOverdue(currentDate)
        if isCheckedOut and currentDate > dueDate then
            return true
        else
            return false
        endif
    endmethod
endobject

8.4 Classes

A class is a blueprint or template for creating objects. It defines the properties and methods that objects of that type will have.

Example 1: Person Class

class Person
    // Class properties (template)
    name = ""
    age = 0
    email = ""
    phoneNumber = ""

    // Constructor method (called when creating new object)
    method constructor(personName, personAge)
        name = personName
        age = personAge
    endmethod

    // Class methods
    method introduce()
        display "Hello, my name is " + name
        display "I am " + age + " years old"
    endmethod

    method celebrateBirthday()
        age = age + 1
        display "Happy birthday! Now " + age + " years old"
    endmethod

    method updateEmail(newEmail)
        email = newEmail
        display "Email updated to: " + email
    endmethod
endclass

// Creating objects from the class
person1 = new Person("Alice", 25)
person2 = new Person("Bob", 30)

// Using the objects
person1.introduce()    // Output: Hello, my name is Alice, I am 25 years old
person2.introduce()    // Output: Hello, my name is Bob, I am 30 years old

person1.celebrateBirthday()  // Alice turns 26

Example 2: Rectangle Class

class Rectangle
    length = 0
    width = 0

    method constructor(l, w)
        length = l
        width = w
    endmethod

    method calculateArea()
        return length * width
    endmethod

    method calculatePerimeter()
        return 2 * (length + width)
    endmethod

    method isSquare()
        return length == width
    endmethod

    method displayInfo()
        display "Rectangle: " + length + " x " + width
        display "Area: " + calculateArea()
        display "Perimeter: " + calculatePerimeter()
        display "Is Square: " + isSquare()
    endmethod
endclass

// Using the Rectangle class
rectangle1 = new Rectangle(5, 3)
rectangle2 = new Rectangle(4, 4)

rectangle1.displayInfo()
rectangle2.displayInfo()

8.5 Relationship Between Classes

Learn how classes can relate to each other through inheritance, composition, and other relationships to create more complex and reusable code structures.

Inheritance Example

// Base class (parent)
class Animal
    name = ""
    age = 0
    species = ""

    method constructor(animalName, animalAge)
        name = animalName
        age = animalAge
    endmethod

    method eat()
        display name + " is eating"
    endmethod

    method sleep()
        display name + " is sleeping"
    endmethod

    method makeSound()
        display name + " makes a sound"
    endmethod
endclass

// Derived class (child) - inherits from Animal
class Dog extends Animal
    breed = ""

    method constructor(dogName, dogAge, dogBreed)
        // Call parent constructor
        super(dogName, dogAge)
        breed = dogBreed
        species = "Canine"
    endmethod

    // Override parent method
    method makeSound()
        display name + " says Woof!"
    endmethod

    // New method specific to Dog
    method fetch()
        display name + " is fetching the ball"
    endmethod
endclass

// Another derived class
class Cat extends Animal
    isIndoor = true

    method constructor(catName, catAge, indoor)
        super(catName, catAge)
        isIndoor = indoor
        species = "Feline"
    endmethod

    method makeSound()
        display name + " says Meow!"
    endmethod

    method climb()
        display name + " is climbing"
    endmethod
endclass

// Using inheritance
myDog = new Dog("Buddy", 3, "Golden Retriever")
myCat = new Cat("Whiskers", 2, true)

myDog.eat()        // Inherited from Animal
myDog.makeSound()  // Overridden in Dog class
myDog.fetch()      // Specific to Dog class

myCat.sleep()      // Inherited from Animal
myCat.makeSound()  // Overridden in Cat class
myCat.climb()      // Specific to Cat class

Composition Example

// Component classes
class Engine
    horsepower = 0
    fuelType = ""

    method constructor(hp, fuel)
        horsepower = hp
        fuelType = fuel
    endmethod

    method start()
        display "Engine started: " + horsepower + "HP " + fuelType
    endmethod
endclass

class Wheel
    size = 0
    type = ""

    method constructor(wheelSize, wheelType)
        size = wheelSize
        type = wheelType
    endmethod
endclass

// Main class using composition
class Car
    engine = null
    wheels[4] = null
    model = ""
    color = ""

    method constructor(carModel, carColor, engineHP, fuelType)
        model = carModel
        color = carColor

        // Composition: Car "has-a" Engine
        engine = new Engine(engineHP, fuelType)

        // Composition: Car "has-a" collection of Wheels
        for i = 0 to 3
            wheels[i] = new Wheel(17, "All-season")
        next i
    endmethod

    method startCar()
        display "Starting " + color + " " + model
        engine.start()  // Using composed object
        display "Car is ready to drive"
    endmethod

    method displaySpecs()
        display "Car: " + color + " " + model
        display "Engine: " + engine.horsepower + "HP " + engine.fuelType
        display "Wheels: " + wheels[0].size + " inch " + wheels[0].type
    endmethod
endclass

// Using composition
myCar = new Car("Sedan", "Blue", 200, "Gasoline")
myCar.startCar()
myCar.displaySpecs()

Course Completion

Congratulations! Upon completing this course, you will have a solid foundation in programming fundamentals. You'll understand how to:

  • Work with variables, constants, and data types
  • Solve problems systematically using algorithms
  • Control program flow with selection structures
  • Use loops for repetitive tasks
  • Organize data with arrays
  • Create reusable code with functions
  • Work with files for data persistence
  • Understand basic object-oriented programming concepts

This knowledge will prepare you for learning specific programming languages and advancing to more complex programming topics.

Next Steps

After completing this course, consider exploring:

  • Specific programming languages (Python, JavaScript, Java, C++)
  • Data structures and algorithms
  • Database programming
  • Web development
  • Mobile app development
  • Software engineering principles

Happy programming! 🚀

Prerequisites

  • Basic computer literacy
  • No prior programming experience required

Course Modules

General Concepts

  • Data Hierarchy
  • Variables and Naming Conventions
  • Constants
  • Using Variables
  • Arithmetic Expressions

Problem Solving and Understanding

  • Problem Solving Fundamentals
  • Understanding the Problem
  • Pseudocode
  • Writing Algorithms

Selection Control Structure

  • Relational Operators
  • Logical Operators
  • Simple If Statement
  • If-then-else Statement
  • Compound If Statement
  • Nested If Statement
  • Select Case Structure

Loops

  • For-next Loop
  • Nested For Statement
  • Do Loops (Pre-test and Post-test)

Arrays

  • What is an Array?
  • Properties of an Array
  • Parallel Arrays
  • Two Dimensional Arrays

Functions

  • Parameters and Arguments
  • Value vs Reference Parameters
  • Calling and Using Functions

Working with Files

  • Opening and Closing Files
  • Reading and Writing to Files

Introduction to Object-Oriented Programming

  • Objects and Properties
  • Methods
  • Classes
  • Relationship Between Classes

Tags

programmingfundamentalsbeginneralgorithmsdata-structures