COMPUTATIONAL THINKING AND PROGRAMMING LOGIC

Simple Study Notes from Section 4


1. ALGORITHMS

What is an Algorithm?

An algorithm is a series of steps that you follow to solve a problem or complete a task. Think of it like a recipe in cooking that tells you what to do, step by step.

Key Characteristics of Algorithms

  1. Input - The data the user enters to start the process
  2. Output - The result or solution based on the given inputs
  3. Definiteness - Each step must be precise and clear
  4. Finiteness - Must have a finite number of steps and eventually end
  5. Effectiveness - Steps should be simple and executable
  6. Language Independence - Can be implemented in any programming language

Types of Algorithms

  1. Sorting Algorithms - Arrange elements in order (e.g., alphabetical)
  2. Mathematical Algorithms - Perform calculations (average, sum, area)
  3. Encryption Algorithms - Encode data for security
  4. Search Algorithms - Find specific elements in data

Real-Life Algorithm Example

Algorithm for a child getting ready for school:
  1. Wake up
  2. Brush teeth
  3. Wash
  4. Dress
  5. Eat breakfast
  6. Get school bag
  7. Travel to school

Visual Representation: Algorithm Process

How Algorithms Work: Problem to Solution PROBLEM Find the sum of 529 and 256 Input: 529, 256 Step 1 ALGORITHM (Step-by-step instructions) 1. Assign x = 529 2. Assign y = 256 3. Calculate z = x + y 4. Output z Definite, Finite, Effective Step 2 SOLUTION 785 Output: 785 ✓ Problem Solved! Key Algorithm Characteristics: Input: 529, 256 | Output: 785 | Definite: Clear steps | Finite: 4 steps | Effective: Simple operations

Simple Math Algorithm Example

Problem: Find the sum of 529 and 256

Pseudocode:

  1. Assign x the value 529
  2. Assign y the value 256
  3. Assign z the sum of x and y
  4. Output the value of z

Python Code:

x = 529
y = 256
z = x + y
print(z)

Output: 785


2. VARIABLES

What is a Variable?

Variables are named storage locations that hold a value or an object which can be changed.

Think of variables as labeled boxes that store information in your program.

Key Points about Variables

Assignment Operator

The assignment operator in Python is the "=" symbol.

Examples:

age = 16
reply = True
cost = 34.56
city = "Kumasi"
console = 'PlayStation'
Note: The "=" means "assign" or "store", NOT "equals"

Example: Using Variables

message = "Python is fun"
print(message)

information = "My message to you is "
print(information + message)  # Join variables with +

Output:

Python is fun
My message to you is Python is fun

3. FLOWCHARTS

What is a Flowchart?

Flowcharts are graphical representations of algorithms that use shapes and arrows to illustrate the sequence of steps in an algorithm.

While pseudocode uses plain text to show steps, flowcharts use shapes to solve the same problem.

Basic Flowchart Symbols

Symbol Name Function
Oval (rounded rectangle) Terminator Shows where a process begins or ends (START/STOP)
Rectangle Processing Shows actions or operations (calculations, assignments)
Parallelogram Input/Output Shows data being entered (input) or displayed (output)
Diamond Decision Shows a choice or condition with different outcomes
Arrow Flow Lines Shows the order of instructions and connections
Circle On-page Connector Links different parts on the same page
Pentagon Off-page Connector Shows flow continues on another page

Flowchart Symbols Visual Reference

START/STOP Terminator x = x + 1 Process Processing INPUT name Input/Output x > 10 ? Decision Flow Line A On-page Connector 1 Off-page Connector Quick Tips: • Ovals mark beginning and end points • Rectangles show calculations or actions • Parallelograms are for user input/output • Diamonds represent yes/no decisions • Arrows show the direction of program flow • Connectors link different parts of flowchart

Flowchart Example: Addition Algorithm

Flowchart: Sum of 529 and 256 START x = 529 y = 256 z = x + y OUTPUT z END Result: 785
Note:

Why Use Flowcharts?


4. DATA STRUCTURES

What are Data Structures?

Data structures are used to organize and store collections of data in a way that makes it easy to access and modify.

They are like building blocks that allow programmers to efficiently store, retrieve, and manipulate data in computer programs.

Importance of Data Structures

  1. Organize and store data efficiently
  2. Enable efficient storage and retrieval of data
  3. Reduce processing time and improve performance
  4. Essential for becoming a programmer
  5. Allow you to write more efficient code

Classifications of Data Structures

1. LINEAR DATA STRUCTURES

Definition: Data elements are arranged in a sequential, end-to-end manner. Each element has predecessors and successors (except first and last).

Characteristics:

Examples:

Real-life Example: People waiting in a queue at a bank or market

2. NON-LINEAR DATA STRUCTURES

Definition: Data elements are not organized sequentially but in an interconnected manner.

Characteristics:

Examples:

Real-life Example: School administration hierarchy (Headmistress → Assistant Heads → Departments)

Comparison Table

Criteria Linear Non-Linear
Data Arrangement Sequential (one after another) Hierarchical or interconnected
Links Each item linked to previous and next Each item linked to many items
Traversing Single run possible Multiple paths needed
Implementation Easy Difficult
Examples Arrays, Stacks, Queues Trees, Graphs

Visual Comparison: Linear vs Non-Linear Data Structures

LINEAR DATA STRUCTURE (Sequential Arrangement) Item 1 Item 2 Item 3 Item 4 Characteristics: ✓ Elements in sequence ✓ One path from start to end ✓ Easy to traverse ✓ Simple implementation Example: Queue at a bank NON-LINEAR DATA STRUCTURE (Hierarchical/Interconnected) Root Child Child Leaf Leaf Leaf Leaf Characteristics: ✓ Elements interconnected ✓ Multiple paths possible ✓ Complex traversal ✓ Advanced implementation Example: School hierarchy

Other Classifications

Static vs Dynamic Data Structures

Static Data Structures:

Dynamic Data Structures:


5. ARRAYS (Linear Data Structure)

What is an Array?

An array is a collection of elements stored in contiguous memory locations. Each element can be accessed by its index (position).

Think of it like: A market list where you neatly arrange items (Akple, Fufu, Kenkey, Banku, Red Red) in rows, making it easy to find, add, or swap items.

Array Structure Visualization

How Arrays Store Data in Memory Each element has an index (position) starting from 0 foods = Index: 0 1 2 3 4 "Akple" "Fufu" "Kenkey" "Banku" "Red Red" Memory: 0x1000 0x1001 0x1002 0x1003 0x1004 Accessing Array Elements: foods[0] returns "Akple" foods[2] returns "Kenkey" Key Point: Arrays use zero-based indexing, meaning the first element is at index 0, not 1!

Example Array in Python

# Creating an array
foods = ["Akple", "Fufu", "Kenkey", "Banku"]

# Accessing elements by index (starts at 0)
print(foods[0])  # Output: Akple
print(foods[2])  # Output: Kenkey

Array Operations

  1. Reverse - Reverse the order of elements
  2. Sort - Arrange elements in order
  3. Search - Find specific elements
  4. Count - Count occurrences of an element
  5. Copy - Duplicate the array

Example: Reversing an Array

activities = ["Morning jog", "Breakfast", "Study"]
print("Original:", activities)

# Reverse the array
activities.reverse()

# Output each element
for activity in activities:
    print(activity)

Output:

Original: ['Morning jog', 'Breakfast', 'Study']
Study
Breakfast
Morning jog

Example: Counting Occurrences

computerList = ["tablet", "desktop", "tablet",
                "smartphone", "supercomputer", "tablet"]

# Count specific items
toCheck1 = "tablet"
toCheck2 = "mainframe"

print("Number of", toCheck1, ":", computerList.count(toCheck1))
print("Number of", toCheck2, ":", computerList.count(toCheck2))

Output:

Number of tablet: 3
Number of mainframe: 0

6. THREE ALGORITHM REPRESENTATIONS

The same algorithm can be represented in THREE different ways:

1. Pseudocode

2. Flowchart

3. Program Code

Key Insight

All three formats achieve the SAME GOAL - they just present the solution in different ways!

Process: Pseudocode → Flowchart → Code


7. SWAP ALGORITHM

What is Swapping?

The swap algorithm is used to exchange the values of two variables without losing data.

Real-World Analogy

Imagine you have two cups:

To swap without spilling:

  1. Get an empty cup (Temp)
  2. Pour water from Cup A into Temp
  3. Pour juice from Cup B into Cup A
  4. Pour water from Temp into Cup B

Now: Cup A has juice, Cup B has water!

Swap Algorithm Steps

  1. Temp = A - Store first value in temporary variable
  2. A = B - Copy second value to first variable
  3. B = Temp - Copy temporary value to second variable

Python Code Example

# Swap Algorithm
a = 49
b = 61
print("Original values:", a, "and", b)

# Swap using temporary variable
temp = a
a = b
b = temp

print("After swap:", a, "and", b)

Output:

Original values: 49 and 61
After swap: 61 and 49

Why Use a Temporary Variable?

Without a temporary variable, we would lose the original value of A when we assign B to it!

Visual Representation: Swap Algorithm

Swapping Two Values Using a Temporary Variable STEP 1: Initial State A 💧 Water (49) B 🧃 Juice (61) Temp Empty STEP 2: Temp = A (Pour water to Temp) A Empty B 🧃 Juice (61) Temp 💧 Water (49) Pour → STEP 3: A = B (Pour juice to A) A 🧃 Juice (61) B Empty Temp 💧 Water (49) Pour → STEP 4: B = Temp (Pour water to B) ✓ SWAP COMPLETE! A 🧃 Juice (61) B 💧 Water (49) Temp Empty Pour → Result: A and B have swapped values! A now has Juice (61), B now has Water (49)

KEY CONCEPTS SUMMARY

Variables - Storage containers that hold values which can change

Algorithms - Step-by-step instructions to solve problems

Flowcharts - Visual representation using standard shapes

Data Structures - Organize and manage data efficiently

Linear Data Structures - Elements arranged sequentially (e.g., Arrays)

Non-Linear Data Structures - Elements interconnected (e.g., Trees, Graphs)

Swap Algorithm - Exchange values using a temporary variable

Three Representations - Pseudocode, Flowchart, and Code all solve the same problem


REMEMBER

Learning to code is like learning a new language - it requires practice and persistence!

Stay curious, ask questions, and keep practicing these fundamental concepts to become a skilled programmer.