Algorithms:


What is it?

An algorithm is a finite set of instructions designed to perform a specific task. It’s it a set of procedures that you follow step-by-step to achieve a desired outcome. For example, when you bake cookies, you follow a series of specific steps to get the final product.

Real World Example:

  • Getting ready in the morning
    • First wake up and brush
    • Wear shirt/pants/socks etc.
    • Eat breakfast

Coding Example (in Python):

def check_for_n(arr, n):
    for i in range(len(arr)):  # iterating through the list
        if n == arr[i]:  # checking if the number exists in the list
            print(f"{True}, {n} exists at index {i}")  # printing the result
            return
    print(f"{False}, {n} does not exist in the given list.")  # printing the result if it doesn't exist

# Defining a list of numbers
array = [3, 8, 12, 6, 10, 2]

# Calling the function with the list and checking for the number 10
check_for_n(array, 10)


Key Components of an Algorithm


Sequencing

What is it?:

It is the order of the steps in an algorithm.

Real World Example:

  • Making a quesidilla
    • FIRST heat the pan
    • SECOND place a tortilla in the pan.
    • THIRD sprinkle cheese over the tortilla.
    • FOURTH place another tortilla on top.
    • FIFTH cook until the bottom tortilla is golden brown, then flip.
    • SIXTH cook until the other side is golden brown and the cheese is melted.
    • SEVENTH remove from the pan and eat.

Selection:

What is it?:

Selection is the process where the code can have a conditional statement and chek whether something is true or not. This is basically the computers way to make decisions in algorithm. We can put this into use when we need to execute a different algorithm or task based on the conditions.

Real World Example:

If it’s hot outside, then wear sunscreen and shorts. Else, go without sunscreen.


Iteration/Repetition

What is it?:

Iteration which is basically just repetition, is when instructions are executing a series of steps repeatedly until a specific condition is fulfilled. This is useful when an action needs to be performed multiple times, often until a particular criterion is met.

Real World Example:

  • Step 1: Bake cookies in the oven.
  • Step 2: Check if they are golden brown
    • If Yes: Stop baking.
    • If No: Repeat starting from Step 1.
# Function to make a cup of tea
def bake_cookies():
    # Sequencing: The steps must happen in the order of the code.
    print("Step 1: Preheat Oven.")
    print("Step 2: Mix the batter for the cookies.")
    print("Step 3: Put the cookie batter on a cookie sheet on a pan.")
    
    # Selection: Making a decision based on a condition.
    has_choc = input("Do you want chocolate chips on your cookie? (yes or no)").strip().lower()
    
    if has_choc == "yes": 
        print("Step 4: Add chocolate chips.")
    else:
        print("Step 4: No chocolate chips added.")
    
    
    print("Step 5: Bake for 30 min.")
    
    # Iteration: Repeating the stirring process until the tea is mixed well.
    is_baked = False
    stir_count = 0
    
    while not is_baked:
        print("Baking...")
        stir_count += 1
        
        if stir_count >= 3: 
            is_baked = True
        
    
    
    print("Cookies are ready to eat!")


bake_cookies()


Ways to Write an Algorithm


Flowchart:

What is it?:

A flowchart is a way to represent an algorithms steps in a visual way or presentation that one can see. It makes use of symbols such as arrows and specific shapes that represent the sequence and order of the steps.

How It Works:

  • Ovals represent the start and end.
  • Rectangles represent instructions or actions.
  • Diamonds represent decisions, often leading to different paths based on Yes/No or True/False conditions.

Example:


Pseudo Code:

What is it?:

Pseudo code is a way that coders can put the code of an algorithm into descriptive steps in english. It helps people understand what is going on in a way that comes naturally to the human brain.

How It Works:

  • Words and sentneces are usually in a list or steps in the form of instructions.
  • It is focused towards the structure and flow rather than the exact syntax and code.

Example

Start
Put on clothes
If it’s hot outside
    Wear suncscreen and shorts
Else
    Don't wear sunscreen
End

PART 2: Mathematical Operations

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus (remainder of a/b): a % b
  • Math in order of operations
a = 10
b = 5

addition = a + b
print(addition) # Output: 15


subtraction = a - b
print(subtraction) # Output: 5

multiplication = a * b
print(multiplication) # Output: 50

division = a / b
print(division) # Output: 2

c = 10
d = 3

modulus = 10 % 3
print(modulus) # Output: 1

e = 7
f = 2

result = (a + b) * (c / d) - e % f
print(result) # Output: 49
#The operations inside the parentheses are performed first,
#then multiplication, division, modulus, and subtraction in that order.

Summary

  1. Algorithms:

Definition: A set of instructions to perform a task. Example: Baking cookies (step-by-step process).

  1. Key Components of an Algorithm:

Sequencing: The order of steps (e.g., making a quesadilla). Selection: Decision-making with conditional statements (e.g., wearing sunscreen if it’s hot). Iteration (Repetition): Repeating steps until a condition is met (e.g., checking if cookies are done baking).

  1. Ways to Write an Algorithm:

Flowcharts: Visual representation of algorithm steps using shapes (ovals, rectangles, diamonds). Pseudocode: Simplified, human-readable instructions that describe code logic.

  1. Mathematical Operations in Python:

Basic arithmetic: addition (+), subtraction (-), multiplication (*), division (/), modulus (%). Example: Applying the order of operations in Python expressions (parentheses first, then other operations).