Principles of Programming – Algorithms and Flowcharts
4. Algorithms
4.1 What is an Algorithm?
• An algorithm is a step-by-step procedure for solving a problem or performing a task.
• It’s like a recipe in cooking:
o Input = ingredients,
o Process = mixing, cooking,
o Output = the final meal.
Formal definition: An algorithm is a finite sequence of well-defined instructions that, when
followed, produces the desired result.
4.2 Characteristics of a Good Algorithm
1. Definiteness – Each step is clear and unambiguous.
o Bad: “Do it until it looks okay.”
o Good: “Repeat 5 times.”
2. Finiteness – Must stop after a certain number of steps.
o (Not an endless loop!)
3. Input – Should accept zero or more inputs.
4. Output – Must produce at least one result.
5. Effectiveness – Should be simple enough to be carried out with basic resources.
4.3 Writing Algorithms (Pseudocode)
• We often use pseudocode (English-like statements) before coding.
• Example problem: Find the sum of two numbers.
START
READ number1
READ number2
sum = number1 + number2
PRINT sum
END
4.4 Example Algorithm – Find the Largest of Two Numbers
START
READ num1, num2
IF num1 > num2 THEN
PRINT "num1 is larger"
ELSE
PRINT "num2 is larger"
ENDIF
END
5. Flowcharts
5.1 What is a Flowchart?
• A flowchart is a visual representation of an algorithm.
• Uses different shapes (symbols) to represent steps.
• Helps programmers see the flow of logic clearly.
5.2 Common Flowchart Symbols
1. Oval (Terminator) → Start/End
o Example: START, END
2. Parallelogram → Input/Output
o Example: Read number, Print result
3. Rectangle → Process/Action
o Example: sum = num1 + num2
4. Diamond → Decision (Yes/No)
o Example: Is num1 > num2?
5. Arrows → Show the flow of control
5.5 Advantages of Flowcharts
• Easy to understand logic.
• Useful for debugging (spot errors in logic).
• Good for documentation (helps others read your program).
5.6 Limitations of Flowcharts
• Can become complex and messy for big problems.
• Hard to update compared to pseudocode.