Write algorithms with decision-making (branching, looping).
What is an Algorithm?
An algorithm is a finite sequence of well-defined, computer-implementable instructions, typically used to solve a class of problems. It's a step-by-step procedure for achieving a desired outcome.
Key Algorithm Concepts
Sequence: Instructions executed in a specific order.
Selection (Branching): Choosing a different path based on a condition (e.g., using if, else if, else).
Iteration (Looping): Repeating a block of instructions multiple times (e.g., using for, while, do-while).
Flowcharts
Flowcharts are diagrams that visually represent the steps of an algorithm. They use standard symbols to show the flow of control.
Common Flowchart Symbols
Symbol
Meaning
Start/Begin
Process/Operation
Decision/Condition
Input/Output
Arrow/Flow Line
End/Stop
Algorithm Examples
Example 1: Check if a number is positive
Algorithm:
Start
Input a number
If the number is greater than 0, then go to step 3.
Otherwise, go to step 4.
Display "The number is positive".
Go to step 5.
Display "The number is not positive".
End
Suggested diagram: Flowchart for checking if a number is positive.
Example 2: Calculate the area of a rectangle
Algorithm:
Start
Input the length of the rectangle
Input the width of the rectangle
Calculate the area: Area = length × width
Display the area
End
Suggested diagram: Flowchart for calculating the area of a rectangle.
Example 3: Find the largest of three numbers
Algorithm:
Start
Input three numbers (a, b, c)
Assume a is the largest
If b is greater than a, then assume b is the largest
If c is greater than b, then assume c is the largest
Display the largest number
End
Suggested diagram: Flowchart for finding the largest of three numbers.
Decision-Making (Branching) in Algorithms
if statements allow algorithms to make choices. The general structure is:
if (condition) then
// Instructions to execute if the condition is true
else
// Instructions to execute if the condition is false
Looping in Algorithms
Loops allow algorithms to repeat a block of instructions. Common types of loops include:
For loop: Repeats a block of instructions a specific number of times.
While loop: Repeats a block of instructions as long as a condition is true.
Do-While loop: Repeats a block of instructions as long as a condition is true, even if the condition is initially false.
Example: Using a For Loop
Algorithm: Print numbers from 1 to 5
Start
For i = 1 to 5 do:
Display the value of i
End for
End
Suggested diagram: Flowchart for printing numbers from 1 to 5 using a for loop.
Example: Using a While Loop
Algorithm: Repeatedly ask for input until a specific value is entered.
Start
Input a number
While the number is not equal to 10 do:
Display "Enter a number (not 10): "
Input a number
End while
Display "You entered 10"
End
Suggested diagram: Flowchart for repeatedly asking for input until 10 is entered using a while loop.