Section 4: Computational Thinking and Programming Logic Flashcards

Introduction to Computational Thinking and Programming Logic

Computational thinking and programming logic involve breaking down complex problems into manageable parts to develop software solutions. This process primarily utilizes algorithms and data structures as foundations for writing efficient code. Programming is the actual process of writing code that instructs a computer, application, or software program on the specific tasks it must perform. Mastery of these concepts is essential in the digital world, requiring practice and persistence similar to learning a new language.

Fundamental Concepts and Key Definitions

Several key concepts form the basis of programming logic. Variables are defined as named storage locations that hold values or objects which can change during the execution of a program. Algorithms are sequential steps used to solve a problem. These can be represented visually using flowcharts, which utilize specific shapes for each step, or through pseudocode, which uses plain text to describe the logic.

Data types categorize the information a computer works with, while data structures provide methods for organizing and storing data to ensure efficient usage. A specific data structure, the array, stores collections of elements of the same data type in a specific order. The Software Development Life Cycle (SDLC) is the structured process used by project managers and developers to design, develop, test, and deploy software.

Variables in Computing

Variables are elements of a program that store information that can vary each time the program is utilized. In physical terms, a computer program is a set of instructions, and the RAM (Random Access Memory) chip on the motherboard contains storage locations that hold the data these instructions manipulate. A variable acts like a container; for example, on a website portal, an index number entered by a user is a variable because it differs depending on the user.

Appropriate variable naming is critical for program clarity. Names should be descriptive, such as \text{Form1_Class_Register} instead of a generic label like xx. Programming languages, including Python, have specific naming rules. Variable names cannot start with numbers (e.g., 1name\text{1name} is invalid, but name1\text{name1} is acceptable). If a name consists of multiple words, spaces are not allowed; instead, programmers use underscores (e.g., \text{first_name} ) or camelCase (e.g., firstName\text{firstName}). In camelCase, the first letter of the second and subsequent words is capitalized.

Characteristics and Types of Algorithms

An algorithm is a series of precise steps followed to complete a task. It functions like a recipe in cooking. For an algorithm to be effective, it must possess several key characteristics:

  1. Input: The data entered by a user to initiate a process.
  2. Output: The result or solution based on the inputs.
  3. Definiteness: Each step must be precise and unambiguous.
  4. Finiteness: The algorithm must terminate after a finite number of steps.
  5. Effectiveness: Steps must be simple enough to be executed by a human with pen and paper or by a computer.
  6. Language Independence: The instructions should be implementable in any programming language while producing the same expected output.

Real-life examples of algorithms include a child's morning routine (Wake up, Brush teeth, Wash, Dress, Eat breakfast, Get school bag, Travel to school, Arrive, Enter premises). Algorithms can be nested; for instance, the process of brushing teeth is an algorithm itself within the larger morning routine. Algorithms can also involve iteration, such as repeating the action of eating porridge until the bowl is empty.

There are several functional types of algorithms:

  • Search Algorithms: Methods for locating specific elements within a data set.
  • Sorting Algorithms: Methods for arranging list elements into a specific order, such as alphabetical or numerical order.
  • Encryption Algorithms: Methods used to encode data for security during storage or transmission, such as HTTPS websites protecting credit card numbers (identity theft prevention\text{identity theft prevention}).
  • Mathematical Algorithms: Procedures for performing math operations, such as calculating the average of two numbers (Average=num1+num22\text{Average} = \frac{\text{num1} + \text{num2}}{2}) or finding the Least Common Multiple (LCM).

Representations of Algorithms: Pseudocode and Flowcharts

Pseudocode refers to the use of plain English text to solve a problem rather than a formal programming language. It is read from top to bottom, and it is considered good practice to number the steps. For example, to find the sum of 529529 and 256256, pseudocode would state: 1. Assign xx the value 529529, 2. Assign yy the value 256256, 3. Assign zz the sum of xx and yy, 4. Output zz.

Flowcharts are graphical representations using specific symbols:

  • Terminator (Oval/Rounded Rectangle): Indicates the Start or Stop of a process.
  • Input/Output (Parallelogram): Shows where information is taken in or given out.
  • Processing (Rectangle): Represents mathematical operations or data manipulation.
  • Decision (Diamond): Indicates a choice or condition, resulting in outgoing flow lines for different outcomes.
  • Flow Lines (Arrows): Show the sequence of instructions.
  • On-page Connector (Circle): Links parts of a flowchart on the same page.
  • Off-page Connector (Home-plate Shape): Shows that a flow continues on a different page, labeled with a matching letter.

Software Development Life Cycle (SDLC)

The SDLC is the method used to create high-quality software that meets client needs efficiently. The process consists of five primary phases:

  1. Analysis: The systems analyst discusses requirements with the client. It involves defining the purpose, functional requirements (Inputs, Processes, Outputs), and identifying assumptions (e.g., assuming all inputs will be valid numbers).
  2. Design: Planning how the software will be built, creating algorithms (pseudocode/flowcharts), defining variables/data types, and designing the User Interface (UI) using wireframes (simple sketches of screen layouts).
  3. Implementation (Coding): Translating designs into a programming language. This stage includes debugging to fix errors.
  4. Testing: Checking the program with various data sets. Testing involves using Normal data (valid inputs), Extreme data (boundary values like 00 or 100100), and Exceptional data (invalid/out-of-range inputs like 82-82).
  5. Maintenance: Fixing issues that arise after delivery, improving the design, or adjusting the program for different operating systems.

Subsequent phases often include Documentation (creating user guides and training materials) and Evaluation (reviewing if the program meets the original requirements).

Error Types in Programming

Errors are classified into three main categories:

  • Syntax Errors: Mistakes in the spelling or grammar of the code (e.g., typing pront\text{pront} instead of print\text{print}). The program will usually fail to run.
  • Run-time Errors: These occur when a program tries to perform an impossible action, such as dividing by zero, causing the program to crash during execution.
  • Logic Errors: Mistakes in the design or formula (e.g., using the wrong mathematical formula for circumference) where the program runs but produces the wrong result.

Data Types and Variables in Python

In Python, data types tell the computer how to handle specific pieces of data. Data can be a single elementary value or a collection of values. Common types include:

  • Integer (int\text{int}): Whole numbers (e.g., 19611961).
  • Floating-point (float\text{float}): Decimal numbers (e.g., 43.543.5).
  • Boolean (bool\text{bool}): True or False values.
  • String (str\text{str}): Sequences of characters (e.g., "Hello World"\text{"Hello World"}).

Python does not require explicit variable declaration; the type is assigned when a value is given. Type conversion functions allow changing data from one type to another, such as using int("123")\text{int("123")} to convert a string to an integer. If a float is converted to an integer (e.g., int(43.5)\text{int(43.5)}), the decimal part is truncated, resulting in 4343. The function type()\text{type()} is used to check the current data type of a variable.

Classifications of Data Structures

Data structures are arrangements for holding multiple values or complex data efficiently. They are categorized based on their organization and memory allocation.

  • Linear Data Structures: Data elements are arranged in a straight path with end-to-end connections. Each element has a predecessor and a successor except the first and last. They can be traversed in a single run. Examples include Arrays, Linked Lists, Stacks, and Queues.
  • Non-Linear Data Structures: Data elements are interconnected rather than sequential. They cannot be traversed in one run and offer flexibility for complex relationships. Examples include Trees and Graphs.
  • Static Data Structures: These have a fixed size allocated at compile time (e.g., standard Arrays). The size cannot change, though the data inside can.
  • Dynamic Data Structures: These grow or shrink during run time (e.g., Linked Lists, Stacks, Trees). Memory is allocated as needed.

Common operations performed on these structures include Searching, Sorting, Insertion, Updating, and Deletion.

Arrays: One-Dimensional and Two-Dimensional

Arrays store multiple items of the same type in contiguous memory locations. Every element shares the same name but has a unique subscript or index. In most languages like Python, Java, and C++, indexing starts at 00. For example, the first element of an array named num\text{num} is num[0]\text{num[0]}.

  • One-Dimensional (1D) Arrays: A single row of elements. Usage examples include storing names of friends (friends = ["Ama", "Kwame", "Kojo"]\text{friends = ["Ama", "Kwame", "Kojo"]}) or exam scores (scores = [75, 88, 92]\text{scores = [75, 88, 92]}).
  • Two-Dimensional (2D) Arrays: Data is organized in a grid with rows and columns, similar to a table. Elements are accessed using two indices (r,cr, c). For example, a table of student marks across different subjects can be modeled as a 2D array where each row is a subject and each column is a student. In Python, this is implemented as a list of lists: marks = [[10, 55], [50, 60]]\text{marks = [[10, 55], [50, 60]]}.

Linked Lists, Stacks, and Queues

  • Linked Lists: A dynamic structure consisting of nodes. Each node contains the data and a reference (pointer) to the next node. Singly linked lists are uni-directional. Doubly linked lists have two pointers per node, allowing traversal both forward and backward. They are used in GPS guidance and browser history (back/forward buttons).
  • Stacks: Lists where items are added or removed only from the top. This follows the LIFO (Last In, First Out) principle. Primary operations are Push (add) and Pop (remove). Stacks are used for undo/redo functions and reversing lists. Exceeding stack capacity causes a "Stack Overflow," while popping from an empty stack causes a "Stack Underflow."
  • Queues: Lists where items join at the back and leave from the front, following the FIFO (First In, First Out) principle. Operations include Enqueuing (adding to the back) and Dequeuing (removing from the front). Applications include printer queues, task scheduling in operating systems, and network data packet sorting.

Graphs and Trees

  • Graphs: Collections of nodes (vertices) connected by lines (edges). They are used to model social media relationships (users as nodes, friendships as edges).
  • Trees: Hierarchical structures where data branches out from a root node. They allow for efficient searching and navigation. Examples include file systems and organizational hierarchies.

Advanced Programming Concepts in Python

Python is a high-level language, meaning its code resembles English. It is compatible with various IDEs (Integrated Development Environments) like IDLE, PyCharm, and Replit.

Core functions and operators include:

  • print(): Displays messages. \text{print("\n")} prints a blank line.
  • input(): Accepts user entry. Input is always received as a string and must be converted (e.g., int(input())\text{int(input())}) for math.
  • Assignment Operator (==): Used to store values in variables.
  • Arithmetic/Comparison Operators: Equals (====), Not equal (!=!=), Exponent (**), Less than or equal (<=<=).
  • f-strings: A method to embed variables in strings, created by placing an ff before the quotes and using braces: print(f"Your age is age")\text{print(f"Your age is {age}")}.
  • List Methods: len()\text{len()} (length), clear()\text{clear()} (remove all), sort()\text{sort()} (arrange), reverse()\text{reverse()} (flip order), count()\text{count()} (count occurrences), and copy()\text{copy()} (duplicate).

The Swap Algorithm

The swap algorithm is used to exchange values between two variables. This typically requires a temporary placeholder (temp\text{temp}) to avoid data loss. The process follows these steps:

  1. Move the value of variable AA to temp\text{temp} (temp=A\text{temp} = A).
  2. Move the value of variable BB to AA (A=BA = B).
  3. Move the value of temp\text{temp} back to BB (B=tempB = \text{temp}). This logic is central to many sorting algorithms like Bubble Sort and Quick Sort.

Conditional Logic: If/Else Statements

If/Else statements allow a program to make decisions based on conditions. If the condition is True, one block of code executes; otherwise, the alternative block executes.

Example specification: If a customer is younger than 1515, they receive a discount. In Python:

age = int(input("How old are you?"))
if age < 15:
    print("You are eligible for a discount.")
else:
    print("You are not eligible for a discount.")

Logic like this is used in everyday applications, such as a provision store at Krofrom deciding whether a student buys a meat pie (cost5\text{cost} \ge 5 GH₵) or a bofrot (cost<5\text{cost} < 5 GH₵).