Master the fundamental concepts of programming including variables, data types, control structures, loops, arrays, functions, and object-oriented programming 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.
By the end of this course, you will understand:
This course is organized into 8 comprehensive modules, each building upon the previous concepts to give you a solid foundation in programming.
Data hierarchy refers to the systematic organization of data, often in a hierarchical form.
Data Organization Involves:
Variables are containers for storing data values.
For Example:
x = 3
y = 6
x stores the value 3 and y stores the value 6
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:
nameaddressJoining two or more words:
studentNamestudent_nameYou 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
A constant is a variable whose value cannot be changed once it has been assigned a value.
In some programming languages, constants are named using all uppercase.
For example:
HOURLY_RATE = 8.50
The assignment symbol (=) is used to assign a value to a variable.
For example:
variableName = value
An arithmetic expression is an expression that results in a numeric value.
| Operator | Description | Example | Results | Precedence |
|---|---|---|---|---|
| ^ | Exponent | 2 ^ 4 | 16 | 1 |
| - | Negation | -True, --6 | False, +6 | 2 |
| *, / | Multiplication and Division | 5 * 7, 72/8 | 35, 9 | 3 |
| \ | Integer division | 37\5 | 7 | 4 |
| mod | Modulus | 37 mod 5 | 2 | 5 |
| +, - | Addition and subtraction | 4 + 7, 14 - 5 | 11, 9 | 6 |
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
Before you can solve a problem, it's essential to understand what the problem is!
Steps to follow to ensure you understand a 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.
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:
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.
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).
| Symbol | Description |
|---|---|
| = | Equal to |
| < | Less than |
| > | Greater than |
| <= | Less than or equal to |
| >= | Greater than or equal to |
| <> | Not equal to |
A logical operator joins two Boolean expressions to yield a Boolean result (True or False).
| Symbol | Description |
|---|---|
| NOT (!) | Returns the opposite |
| AND (&&) | Returns True if both expressions are True |
| OR (||) | Returns True if one expression is True |
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
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
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
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
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
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
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
There are two types of Do loop:
The condition is tested before the statements within the loop are processed.
Syntax:
do while number < 10
code block to be executed
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
An array is a collective name given to a group of similar quantities.
For example:
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
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
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:
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"
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
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
The syntax for calling a function is:
functionName(argument list)
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
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.
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"
| Mode | Description | Usage |
|---|---|---|
| Read | Open file for reading only | Viewing existing data |
| Write | Open file for writing (overwrites existing) | Creating new files |
| Append | Open file for writing at the end | Adding to existing files |
Master the techniques for reading data from files and writing data to files, essential skills for data persistence and file processing.
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
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
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
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:
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
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
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
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()
Learn how classes can relate to each other through inheritance, composition, and other relationships to create more complex and reusable code structures.
// 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
// 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()
Congratulations! Upon completing this course, you will have a solid foundation in programming fundamentals. You'll understand how to:
This knowledge will prepare you for learning specific programming languages and advancing to more complex programming topics.
After completing this course, consider exploring:
Happy programming! 🚀