Lesson 66: Worked Examples of Algorithms

Example 1: Sequence Algorithm

Write an algorithm to calculate the sum of the first n positive integers.

  1. Input n
  2. Initialize sum = 0
  3. For i = 1 to n
  4. sum = sum + i
  5. Output sum

Example 2: Selection Algorithm

Write an algorithm to find the maximum of two numbers.

  1. Input a and b
  2. If a > b then
  3. Output a
  4. Else
  5. Output b

Example 3: Iteration Algorithm

Write an algorithm to calculate the factorial of a given number n.

  1. Input n
  2. Initialize factorial = 1
  3. For i = 1 to n
  4. factorial = factorial x i
  5. Output factorial

Example 4: Recursion Algorithm

Write an algorithm to calculate the Fibonacci sequence up to the nth term.

  1. Input n
  2. If n = 1 then
  3. Output 0
  4. Else if n = 2 then
  5. Output 1
  6. Else
  7. Output fib(n-1) + fib(n-2)

Designing Solutions

Use structured diagrams and pseudocode to construct solutions. Decompose problems into smaller parts and design a solution for each part. For example, a grade management system can be designed using structured diagrams and pseudocode in the same way.

Leave a comment

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

sponsors Ads