Home

Computational Thinking Algorithm in Programming

By ITE 300L Group 51 (Peter and Isaiah)

Computational Thinking

Computational thinking refers to the cognitive processes and problem-solving techniques used by computer scientists and programmers to tackle complex problems. It involves breaking down problems into smaller, more manageable parts and devising algorithms to solve them. Computational thinking encompasses various forms that help individuals approach problems from different perspectives. Here are some key forms of computational thinking:

  1. Decomposition:
    • Breaking down complex problems into smaller, manageable sub-problems or tasks.
    • Focuses on dividing a problem into parts that can be solved independently and then integrating those solutions.
  2. Pattern Recognition:
    • Identifying recurring patterns or similarities within data or problems.
    • Helps in recognizing similarities between different problems and applying solutions from one domain to another.
  3. Abstraction:
    • Focusing on the essential details while ignoring unnecessary complexities.
    • Involves creating models or representations that capture the essential aspects of a problem.
  4. Algorithmic Design:
    • Developing step-by-step procedures (algorithms) to solve problems.
    • Emphasizes creating clear, systematic, and efficient methods for solving problems.
  5. Algorithmic Analysis:
    • Evaluating and comparing algorithms based on factors like time complexity, space complexity, and efficiency.
    • Helps in selecting the most suitable algorithm for a specific problem.

What is Algorithm?

In programming, an algorithm refers to a step-by-step procedure or set of instructions designed to perform a specific task or solve a problem. It is a well-defined, finite sequence of operations that takes input data, processes it, and produces the desired output. Algorithms are fundamental to computer programming as they provide the logic and structure necessary for writing efficient and effective code.

Programmers use algorithms to solve a wide range of problems, from simple tasks like sorting an array to complex operations like searching through vast databases or optimizing routes in a navigation system. The choice of algorithm can significantly impact the performance and effectiveness of a program, making algorithm design a critical skill for programmers.

You can learn about algorithm here

The Three Basic Programming Constructs

Programs are designed using common building blocks. These building blocks, known as programming constructs, form the basis for all programs. There are three basic building blocks to consider:

  • sequence
  • selection
  • iteration

Sequence is the order in which instructions occur and are processed. Selection determines which path a program takes when it is running. Iteration is the repeated execution of a section of code when a program is running. There are two types of iteration:

  • count-controlled iteration
  • condition-controlled iteration

All programs use one or more of these constructs. The longer and more complex the program, the more these constructs will be used repeatedly. This guides uses pseudo-code examples to illustrate the constructs. It is important to realize that while all programming languages include these constructs, there may be slightly different formats.

Sequence

Sequence is the first programming construct. In programming, instructions are executed one after another. Sequence is the order in which the instructions are executed. The sequence of instructions is extremely important as carrying out instructions in the wrong order results in a program performing incorrectly.

Sequence refers to the order in which individual statements or instructions are executed in a program. The code is executed sequentially from the top to the bottom, one statement after another. It is the most basic construct and is used to ensure that steps are performed in a specific order. Example

print(“Step 1”)
print(“Step 2”)
print(“Step 3”)

In this example, the statements will be executed in the given sequence: Step 1, Step 2, Step 3.

To learn more about Sequence, download this pdf below.

Selection

Selection is the second programming construct. In programming, there are occasions when a decision needs to be made. Selection is the process of making a decision. The result of the decision decides which path the program will take next.

Selection involves making decisions based on certain conditions. It allows the program to choose between different paths of execution depending on the evaluation of conditions (e.g., if-else statements). Example

x = 10
if x > 0:
print(“Positive”)
else:
print(“Non-positive”)

In this example, the program checks if ‘x’ is greater than 0. If true, it prints “Positive,” and if false, it prints “Non-positive.” Selection allows the program to make choices based on conditions.

To learn about selection, download this pdf below

Iteration

In programming, iteration is a programming construct that allows you to repeat a set of instructions or a block of code multiple times. It provides a way to execute the same sequence of statements repeatedly until a certain condition is met or a specific number of iterations are completed. Iteration is an essential concept for implementing loops in programming languages.

There are two main types of iteration constructs: for loops and while loops. Both for and while loops are powerful constructs in programming, allowing developers to implement repetitive tasks efficiently and concisely. However, it’s important to ensure that the condition provided in the loop is designed in a way that eventually becomes false; otherwise, the loop can result in an infinite iteration, leading to program errors or crashes.

Iteration involves repeating a set of statements or a block of code multiple times until a specific condition is met. Loops are used to achieve iteration in programming. Example

for i in range(5):
print(i)

In this example, the loop will run five times, printing the numbers from 0 to 4. Iteration is useful when you need to perform repetitive tasks or process data elements one by one.

Learn more about iteration (loops) here

A Simple Program Using the Basic Programming Constructs(Sequence, Selection, and Iteration)

Here’s a simple program in Python that calculates the factorial of a given positive integer using sequence, selection (conditional statements), and iteration (loop)

This program follows these programming constructs:

  1. Sequence: The code is executed sequentially, from top to bottom, following the order of statements.
  2. Selection (Conditional Statements): The program checks if the input number is positive or negative. If it’s negative, it displays an error message; otherwise, it proceeds to calculate the factorial.
  3. Iteration (Loop): A for loop is used to calculate the factorial by multiplying the numbers from 1 to num.

This program demonstrates the use of sequence (step-by-step execution), selection (if-else condition), and iteration (for loop) constructs to solve a simple problem.

Decomposition

Decomposition involves breaking down a complex problem or system into smaller parts that are more manageable and easier to understand. The smaller parts can then be examined and solved, or designed individually, as they are simpler to work with. The process of formulating and solving problems by breaking them down into simple steps. It is a powerful problem-solving technique that equips us to solve complex problems in the modern world.

Abstraction

Abstraction is the process of filtering out – essentially ignoring – the characteristics of problems that are not needed in order to concentrate on those that are needed. It is also the filtering out of specific details. From this, an idea of what is to be solved can be created.

Abstraction allows us to create a general idea of what the problem is and how to solve it. The process instructs us to remove all specific detail and any patterns that will not help us solve our problem. This helps us forms our idea of the problem. This idea is known as a ‘model’.

The difference between Decomposition and Abstraction

A lot of students mostly get confused of the difference between decomposition and abstraction, the difference is very simply.

Decomposition is about breaking a problem into smaller parts, while Abstraction is about hiding the unnecessary details and providing a simplified view of a complex system. Decomposition helps in managing complexity by dividing a large problem into manageable pieces, while abstraction helps in managing complexity by simplifying the interfaces and interactions with those pieces. Both concepts play vital roles in creating efficient, maintainable, and scalable software solutions.

How to use Decomposition and Abstraction in Programs

Applying decomposition and abstraction in writing a program involves structuring the code into smaller, manageable components and abstracting away implementation details to provide a simplified interface.

In this example, we decompose the problem into functions for calculating the area of each shape. We also apply abstraction by providing a high-level interface calculate_area that hides the details of the individual area calculation functions. Users can interact with this interface by providing the shape and necessary parameters, without needing to know how the calculations are done internally.

Consider the problem of how a program that calculates the sum of all even numbers from 1 to a given positive integer ‘n’.

In this code above, we first check if the input ‘n’ is a positive integer. If not, we ask the user to enter a positive integer. Then, we calculate the sum of all even numbers from 1 to ‘n’ using the ‘sum_of_even_numbers‘ function and display the result. The functions ‘is_even‘ and ‘sum_of_even_numbers‘ encapsulate specific tasks, abstracting the underlying complexity. The loop in the ‘sum_of_even_numbers‘ function demonstrates the concept of iteration, and the overall order of execution follows the sequence. This approach makes the code easier to read, maintain, and understand.

Let’s consider a computational problem: calculating the factorial of a given positive integer. Factorial of a number is the product of all positive integers less than or equal to that number.

Problem: Calculate the factorial of a given positive integer n.

Decomposition:

  1. Input: Get the value of n from the user.
  2. Factorial Calculation: a. Initialize a variable factorial to store the result. b. Iterate from 1 to n. c. Multiply each number from 1 to n with the current value of factorial.
  3. Output: Display the calculated factorial.

Here’s the Python code implementing the decomposition to solve the factorial problem

In this example, we’ve broken down the problem into three steps: input, factorial calculation, and output. By following this decomposition, we’ve created a clear and organized solution to calculate the factorial of a given positive integer.

Linear Search

Linear search also known as sequential search, is an algorithm for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. This is one of the most basic search algorithms and is directly, inspired by real-life events. The example below shows the algorithm and pseudocode for linear search.

Algorithm

Step 1: set x to 1
Step 2: if x > n then go to Step 7
Step 3: if A[x] = x then go to step 6
Step 4: Set x to X +1
Step 5: Go to Step 2
Step 6: Print Element at index x and go to step 8
Step 7: Print element not found
Step 8: Exit
Step 1: Traverse the array

Step 2: Match the key element with array element
Step 3: if key element is found, return the index position of the array element
Step 4: if key element is not found, return -1
Linear Search (Array A, Value x)

Pseudocode

procedure linear_search (list, value)
  for each item in the list
      if match item == value
         return the iterms location
      end if
  end for
end procedure

A Linear search is the simplest algorithm used in searching a value or data

The step in locating the position of a given in a list.

Let’s say we want to find the position of the value 2 in this list:

  1. Start from the first element in the list, which is 0 at index 0.
  2. Compare the target value 2 with the current element 0. They are not the same.
  3. Move to the next element in the list, which is 5 at index 1.
  4. Compare the target value 4 with the current element 2. They are not the same.
  5. Move to the next element in the list, which is 2 at index 2.
  6. Compare the target value 2 with the current element 2. They are the same.
  7. Since we found the target value 2 at index 2, we return the index, which is 2.

So, the position of the value 2 in the list is 2. Keep in mind that linear search is a simple and sequential way of finding a value, and it checks each element one by one until the target is found or the end of the list is reached.

The example above is a real-world scenario, it has more than one option to choose from at the Got Ghc150? option but it still achieves the same outcome with any of the options taken.

Variables in Programming

In programming, a variable is a named storage location that holds a value or data. It serves as a way to store and manipulate data in a program. Variables allow you to reference and work with data without knowing its actual value at compile time.

Key Characteristics of Variables:

  1. Name: Variables have a name that is used to identify and access them. The name should follow certain naming conventions and rules defined by the programming language.
  2. Type: Variables have a data type that defines the kind of data they can hold. Common data types include integers, floating-point numbers, characters, strings, boolean values, and more.
  3. Value: Variables can hold a value of their specified data type. The value can be assigned when the variable is created or later in the program.
  4. Scope: Variables have a scope, which determines where the variable can be accessed or used within the program. Scope can be local (limited to a specific block of code) or global (accessible throughout the program).
  5. Lifetime: Variables have a lifetime that defines how long they exist in memory. They are created when defined and are destroyed when they go out of scope or are no longer needed.

In this Python example, we define several variables (age, name, salary, is_student) and assign them values. We use these variables in calculations and display their values using the print function. Variables play a crucial role in programming, allowing us to manipulate and work with data dynamically as our program runs.

Learn more about Variable here

Constants in Programming

In programming, a constant is a fixed value that cannot be changed or modified during the execution of a program. It is a way to represent a value that remains constant throughout the program’s execution. Constants are often used to provide meaningful names to values that have a specific significance or to avoid hardcoding values directly into the code. Example

# Defining constants
PI = 3.14159
MAX_ATTEMPTS = 5
DEFAULT_USERNAME = "guest"

# Using constants in calculations
radius = 5
area = PI * radius * radius

# Constants cannot be modified
# MAX_ATTEMPTS = 10  # This would result in an error

print("The area of a circle with radius", radius, "is:", area)

In this Python example, we define three constants: PI, MAX_ATTEMPTS, and DEFAULT_USERNAME. These constants represent values that should remain constant throughout the program. We use the PI constant in a calculation to find the area of a circle and demonstrate that constants cannot be modified after they are defined.

The Various Ways of Writing a Program


Writing a program involves multiple steps and approaches to create code that accomplishes a specific task or solves a problem. Here’s an outline of various ways to write a program:

  1. Understanding the Problem:
    • Analyze the problem statement to understand the requirements and desired outcomes.
    • Identify the inputs, outputs, constraints, and any special cases.
  2. Algorithm Design:
    • Develop a high-level plan or algorithm to outline the steps for solving the problem.
    • Break down the problem into smaller sub-problems or tasks.
  3. Choosing a Programming Language:
    • Select a suitable programming language based on the problem requirements, your familiarity, and available tools.
  4. Choosing a Development Environment:
    • Set up a code editor or integrated development environment (IDE) to write and test your code.
  5. Writing Code:
    • Translate the algorithm into code using the chosen programming language.
    • Use appropriate data structures, functions, and control flow statements.
  6. Testing and Debugging:
    • Test your code with various inputs to ensure it produces the expected results.
    • Identify and fix any errors (bugs) that arise during testing.
  7. Refactoring and Optimization:
    • Review your code for improvements in efficiency, readability, and maintainability.
    • Refactor code to make it more organized and follow best practices.
  8. Documentation:
    • Add comments and documentation to explain the purpose of functions, algorithms, and complex sections of code.
    • Provide instructions on how to use and run the program.
  9. Version Control:
    • Use version control systems (e.g., Git) to track changes and collaborate with others if necessary.
  10. Building and Compilation:
  • Compile the code (if applicable) to generate an executable file or bytecode.
  1. Testing Again:
  • Conduct thorough testing after any changes to ensure the program still works as intended.
  1. Deployment:
  • Deploy the program to the target environment (e.g., a web server, app store, or local machine).
  1. User Interaction:
  • Create a user interface if needed (e.g., graphical interface, command-line interface).
  • Implement user input and interaction as required by the program.
  1. Error Handling:
  • Implement error handling mechanisms to gracefully handle unexpected situations.
  1. Documentation and Help:
  • Provide user documentation and help resources to guide users on how to use the program.
  1. Maintenance and Updates:
  • Continuously monitor and maintain the program, addressing issues and making updates as needed.

Each of these steps contributes to the process of writing a program, and the specific approach may vary based on the project, programming language, and development environment.

Podcast

Video

In conclusion, this article has aimed to shed light on the key principles that pave the way for successful learning. As students, you hold the power to shape your educational journey by embracing effective strategies, cultivating a growth mindset, and nurturing a genuine passion for knowledge. Remember, learning is not just about acquiring facts; it’s about honing critical thinking, fostering creativity, and nurturing a sense of curiosity that propels you forward. By harnessing the tools and insights shared here, you are well-equipped to navigate the vast sea of information and emerge as empowered learners, ready to conquer the challenges and seize the opportunities that lie ahead. As you embark on this intellectual adventure, embrace the process, embrace your potential, and let the pursuit of learning be a lifelong companion on your path to personal and academic excellence.

Answer the questions below

1.What is an Algorithm
2.Explain the following:
i.Sequence
ii.Selection
iii.Iteration
3.What is the difference between decomposition and abstraction?
4.How does Linear Search works?
5.List three key characteristics of a variable.
6.Create a Python program that takes a user’s age as input and determines whether they are eligible to vote or not. Use basic programming constructs such as sequence, selection (conditional statements), and iteration (loop) in your program. Provide a clear explanation of how each construct is utilized to achieve this task

Submit your work to the class prefect before 30th August, 2023. Thank you.



Testimonial Profile Image

“Thank you for being a remarkable teacher who makes learning engaging and enjoyable. Your dedication and passion for teaching have truly inspired me to reach for my goals.”

— Bayou Vitus, Class Prefect


Testimonial Profile Image

“Your teaching style is like no other. You manage to turn even the most challenging topics into something understandable and interesting. You’ve made a positive impact on my academic journey.”

— Dery Mathias, A Student

5 thoughts on “Home

  1. Thank you for sharing this insightful article, and your passion for teaching truly shines through in your words. Your dedication to our education is greatly appreciated.

    1. Thanks Jonathan, I’m so glad to hear that the article helped deepen your understanding. It’s my goal to make complex concepts accessible, both in the classroom and through my writing.

  2. Reading this article has given me a new perspective on the topic. Your ability to make learning enjoyable extends beyond the classroom, and I’m grateful for that.

    1. Thank you Robert for your kind words! I’m thrilled that the article resonated with you and that you find value in my approach to teaching

  3. Thank you for making learning a collaborative and engaging experience. Your willingness to share your knowledge through articles like this enriches our educational journey.

Leave a Reply

Your email address will not be published. Required fields are marked *