Example 1: Sequence Algorithm
Write an algorithm to calculate the sum of the first n positive integers.
- Input n
- Initialize sum = 0
- For i = 1 to n
- sum = sum + i
- Output sum
Example 2: Selection Algorithm
Write an algorithm to find the maximum of two numbers.
- Input a and b
- If a > b then
- Output a
- Else
- Output b
Example 3: Iteration Algorithm
Write an algorithm to calculate the factorial of a given number n.
- Input n
- Initialize factorial = 1
- For i = 1 to n
- factorial = factorial x i
- Output factorial
Example 4: Recursion Algorithm
Write an algorithm to calculate the Fibonacci sequence up to the nth term.
- Input n
- If n = 1 then
- Output 0
- Else if n = 2 then
- Output 1
- Else
- 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.