Computer Science (2210)
Topic 5 of 10Cambridge O Levels

Algorithms & Programming

Mastering problem-solving using flowcharts, pseudocode, and core programming constructs.

What You'll Learn
An algorithm is a logical, step-by-step set of instructio…Decomposition is the process of breaking down a complex p…Abstraction is the process of ignoring unnecessary detail…Flowcharts and pseudocode are tools used to design and re…

**1. Introduction & Core Concept**


Assalamu Alaikum, future leaders of Pakistan. My name is Dr. Amir Hussain, and for the next few minutes, I want you to forget about computers. Instead, I want you to think about planning the perfect family trip from your home in Lahore to the beautiful valleys of Hunza during the summer holidays.


What is the first thing you do? You don't just jump in the car. You plan.


  1. Break it down (Decomposition): You list the major tasks. Book a hotel. Arrange transport (flight to Gilgit or drive?). Pack bags. Plan daily activities.
  2. Ignore irrelevant details (Abstraction): When booking a flight, you focus on the departure time, price, and airline. You don't worry about the specific model of the Airbus A320 or the name of the pilot. You trust that the system will handle those details.
  3. Create a step-by-step plan (Algorithm):

* Step 1: Check flight prices on PIA's website.

* Step 2: If prices are affordable, book them. Otherwise, plan the driving route.

* Step 3: Search for hotels in Karimabad.

* Step 4: For each hotel, check reviews.

* Step 5: Book the hotel with the best reviews and price.

* ...and so on, until the plan is complete.


This logical, step-by-step plan is the very essence of what we call an algorithm. In computer science, we are not just coders; we are problem-solvers. The computer is a powerful but fundamentally unintelligent tool. It does *exactly* what we tell it to do, and nothing more. Therefore, our instructions must be perfect: clear, precise, and logically sound.


The big-picture mental model is this: You are the architect, the computer is the construction worker. Before a single brick is laid for a building, the architect creates a detailed blueprint. Our "blueprints" in computing are flowcharts and pseudocode. They allow us to design, test, and perfect our logic before we write a single line of code in a programming language like Python, Java, or C++. Mastering this planning stage is the single most important skill that separates a novice from an expert programmer. It is the foundation upon which all software, from the app you use to order food to the systems that manage our nation's power grid, is built.


**2. Theoretical Foundation**


Let's dissect the core principles that form the bedrock of algorithmic thinking.


What is an Algorithm?


The definition you often hear is "a set of rules for solving a problem." This is true, but incomplete. A true algorithm, in the context of computer science, must possess five crucial properties:


  1. Finiteness: It must terminate after a finite number of steps. An algorithm that runs forever is a useless one (this is called an infinite loop).
  2. Definiteness (Unambiguous): Every step must be precisely and clearly defined. There should be no room for interpretation. "Add a little salt" is a fine instruction for a chef, but a terrible one for a computer. It must be "Add 2 grams of salt."
  3. Input: An algorithm has zero or more inputs – quantities that are given to it before it begins.
  4. Output: An algorithm has one or more outputs – quantities that have a specified relation to the inputs. This is the result, the solution to the problem.
  5. Effectiveness: Every instruction must be basic enough that it can, in principle, be carried out by a person using only a pencil and paper. Each step must be feasible.

The Twin Pillars of Design: Decomposition & Abstraction


We mentioned these in our Hunza trip example. Let's formalise them.


* Decomposition: This is the strategy of "divide and conquer." When faced with a large, daunting problem (e.g., "Create a school management system"), we break it down into smaller, self-contained, and more manageable sub-problems.

* Sub-problem 1: A module to handle student admissions.

* Sub-problem 2: A module to manage class timetables.

* Sub-problem 3: A module for recording exam results.

* Sub-problem 4: A module to calculate and issue fee bills.

Each sub-problem can then be solved independently, often by different teams, before being integrated into the final system. This is the only way complex software can be built.


* Abstraction: This is the art of hiding complexity to focus on what is essential. When you drive a car, you use a steering wheel, accelerator, and brake. You are interacting with an *abstraction*. You don't need to know the intricate details of the internal combustion engine, the fuel injection system, or the hydraulic brake lines. You only need to know that pressing the accelerator makes the car go faster. In programming, we do the same. We create procedures and functions that perform a specific task (e.g., `CalculateAverage()`). When we use this function, we don't need to see the code inside it; we just trust that it will return the correct average. This simplifies our main program immensely.


Representing Algorithms: Flowcharts vs. Pseudocode


We have two primary tools for designing our algorithmic "blueprints."


1. Flowcharts: The Visual Blueprint


A flowchart is a diagram that shows the "flow" of control in an algorithm. Its power is its visual nature, making it easy to trace the logic and spot potential issues. It uses a set of standard symbols connected by arrows.


* Terminator (Oval): Every flowchart must have exactly one START and at least one END (or STOP). This enforces the "finiteness" property of an algorithm.

* Input/Output (Parallelogram): This symbol is used for any action that requires interaction with the outside world, like getting a number from the user (`INPUT Num`) or displaying a message on the screen (`OUTPUT "Hello"`). The slanted shape visually suggests movement of data into or out of the program.

* Process (Rectangle): This is the workhorse symbol. Any calculation, assignment of a value to a variable, or data manipulation happens here. Examples: `Count = Count + 1`, `Price = Cost * 1.25`.

* Decision (Diamond): This is where the logic branches. It always contains a question that can be answered with "Yes" or "No" (or "True" or "False"). For example: `Is Age > 18?`. Two arrows must exit a diamond, one for the "Yes" path and one for the "No" path. This is the symbol for selection.

* Flow Lines (Arrows): These connect the symbols and indicate the direction of flow, from top to bottom and left to right, unless an arrow explicitly points elsewhere (like in a loop).


2. Pseudocode: The Structured English Blueprint


Pseudocode (literally "false code") is a way of describing an algorithm using structured English-like statements. It is not a real programming language, so it has no strict syntax rules. However, to ensure clarity and consistency, Cambridge examiners expect you to use a standard set of keywords.


* Purpose: It acts as a perfect intermediate step between a high-level idea and the low-level, syntax-heavy code of a language like Python. It allows you to focus purely on the logic without worrying about semicolons, brackets, or specific command names.


* Standard Keywords (Cambridge O Level):

* `DECLARE : `: To create a variable (e.g., `DECLARE Score : INTEGER`).

* `INPUT `: To get data from the user.

* `OUTPUT `: To display data.

* `IF...THEN...ELSE...ENDIF`: For making decisions (selection).

* `CASE...OF...OTHERWISE...ENDCASE`: For selecting from multiple options based on a single variable's value.

* `FOR = TO ...NEXT `: A count-controlled loop. Use when you know exactly how many times you need to repeat something.

* `WHILE ...DO...ENDWHILE`: A pre-condition loop. The condition is checked *before* each iteration. The loop may not run at all.

* `REPEAT...UNTIL `: A post-condition loop. The condition is checked *after* each iteration. The loop will always run at least once.


The Three Fundamental Programming Constructs


Amazingly, any algorithm, no matter how complex, can be constructed from just three basic patterns of control flow.


  1. Sequence: The default construct. It is the simple execution of one instruction after another, in the order they are written.

* *Example:* `INPUT Radius`, `Area = 3.142 * Radius * Radius`, `OUTPUT Area`.


  1. Selection: This is when the program must choose between two or more alternative paths. This is where the `IF...THEN...ELSE` statement (the diamond in a flowchart) comes in.

* *Example:* `IF Marks >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF`.


  1. Iteration (or Repetition/Looping): This is used when a block of code needs to be executed multiple times.

* Count-controlled (FOR loop): Used when the number of repetitions is known beforehand. "Repeat this 11 times for each player in a cricket team."

* Condition-controlled (WHILE or REPEAT loops): Used when the loop continues as long as a certain condition is true (or until a condition becomes true). "Keep asking for the password UNTIL the correct one is entered."


Understanding how to combine these three simple constructs is the key to designing any algorithm you will face in your O Level exams and beyond.


**3. Key Definitions & Formulae**


This section serves as your quick reference guide. There are no mathematical formulae here, but the syntax and structure are just as rigid and important.


Algorithm Properties

* Algorithm: A finite, ordered set of unambiguous, executable steps that defines a terminating process.

* Decomposition: Breaking a complex problem into smaller, manageable sub-problems.

* Abstraction: Hiding unnecessary detail to focus on the essential features of a problem.


Flowchart Symbols

| Symbol | Name | Purpose |

| :--- | :--- | :--- |

| Oval | Terminator | `START` or `END` of the algorithm. |

| Parallelogram | Input/Output | `INPUT` data from user, `OUTPUT` data to screen. |

| Rectangle | Process | Perform a calculation or assign a value (e.g., `x = 5`). |

| Diamond | Decision | Ask a Yes/No question to split the path (e.g., `Is x > 10?`). |

| Arrow | Flow Line | Connects symbols and shows the direction of logic. |


Pseudocode Keywords & Syntax (Cambridge Standard)

* Variable Declaration:

* `DECLARE : `

* *Example:* `DECLARE StudentName : STRING`, `DECLARE TotalMarks : INTEGER`


* Input/Output:

* `INPUT `

* `OUTPUT `

* *Example:* `INPUT StudentName`, `OUTPUT "Your final score is: ", TotalMarks`


* Assignment:

* ` = `

* *Example:* `Price = 150`, `Counter = Counter + 1`


* Selection (Conditional Statements):

* IF Statement:

`IF THEN`

` `

`ELSE`

` `

`ENDIF`

* CASE Statement:

`CASE OF `

` : `

` : `

` ...`

` OTHERWISE: `

`ENDCASE`


* Iteration (Loops):

* Count-Controlled Loop:

`FOR = TO `

` `

`NEXT `

* Pre-Condition Loop:

`WHILE DO`

` `

`ENDWHILE`

* Post-Condition Loop:

`REPEAT`

` `

`UNTIL `


**4. Worked Examples**


Let's apply this theory to practical problems. I will show the thought process, the flowchart, and the pseudocode for each.


Example 1: Simple Sequence - Currency Conversion


Problem: Design an algorithm that takes an amount in Pakistani Rupees (PKR) from the user, converts it to US Dollars (USD), and displays the result. Assume the conversion rate is 1 USD = 280 PKR.


Thought Process:

  1. Start.
  2. Need the amount in PKR. This is an input. Let's call the variable `PKR_Amount`.
  3. Need to perform a calculation. The formula is `USD_Amount = PKR_Amount / 280`. This is a process.
  4. Need to show the result to the user. This is an output.
  5. End.

Flowchart:

+-----------+

| START |

+-----------+

|

v

+--------------------+

| INPUT PKR_Amount |

+--------------------+

|

v

+-----------------------------+

| USD_Amount = PKR_Amount/280 |

+-----------------------------+

|

v

+----------------------------+

| OUTPUT "USD:", USD_Amount |

+----------------------------+

|

v

+-----------+

| END |

+-----------+


Pseudocode:

DECLARE PKR_Amount : REAL

DECLARE USD_Amount : REAL


OUTPUT "Please enter the amount in PKR:"

INPUT PKR_Amount


USD_Amount = PKR_Amount / 280


OUTPUT "The equivalent amount in USD is: ", USD_Amount

*Note: We use the `REAL` data type because currency can have decimal points.*




Example 2: Selection - WAPDA Electricity Bill Calculation (Karachi Context)


Problem: K-Electric in Karachi has a simplified tariff system. If a user consumes 200 units or less, the rate is Rs. 25 per unit. If they consume more than 200 units, the rate is Rs. 35 per unit. Design an algorithm to calculate a user's bill.


Thought Process:

  1. Start.
  2. Need the number of units consumed. This is an input. Let's call it `Units`.
  3. Here's the key part: we have a choice. We need to check IF the units are less than or equal to 200. This is a decision.
  4. Path 1 (Yes): If `Units <= 200`, the calculation is `Bill = Units * 25`. This is a process.
  5. Path 2 (No): If `Units > 200`, the calculation is `Bill = Units * 35`. This is another process.
  6. After the calculation, the paths merge.
  7. We need to display the final bill. This is an output.
  8. End.

Flowchart:

+-----------+

| START |

+-----------+

|

v

+----------------+

| INPUT Units |

+----------------+

|

v

+----------------+

| Is Units<=200? |<>--No--+

+----------------+ |

| |

Yes v

| +-----------------+

| | Bill = Units*35 |

v +-----------------+

+-----------------+ |

| Bill = Units*25 | |

+-----------------+ |

| /

+----------------+

|

v

+----------------+

| OUTPUT Bill |

+----------------+

|

v

+-----------+

| END |

+-----------+


Pseudocode:

DECLARE Units : INTEGER

DECLARE Bill : REAL


OUTPUT "Enter the number of units consumed:"

INPUT Units


IF Units <= 200 THEN

Bill = Units * 25

ELSE

Bill = Units * 35

ENDIF


OUTPUT "Your total electricity bill is: Rs. ", Bill




Example 3: Iteration - Cricket Team Average Score


Problem: Design an algorithm to calculate the average score of the 11 players in a cricket team. The algorithm should take each player's score as input.


Thought Process:

  1. Start.
  2. We need a variable to store the sum of all scores. Let's call it `TotalScore`. It's crucial to initialise this to 0. This is a process.
  3. We need to repeat a set of actions 11 times. This signals a FOR loop.
  4. Inside the loop:

a. Ask for a player's score. This is an input. Let's call it `PlayerScore`.

b. Add this score to our running total: `TotalScore = TotalScore + PlayerScore`. This is a process.

  1. After the loop finishes: We have the total score for 11 players.
  2. Calculate the average: `AverageScore = TotalScore / 11`. This is a process.
  3. Display the result. This is an output.
  4. End.

Flowchart:

*(Flowcharts for loops can be complex to draw in text, but the logic is as follows: A flow line comes from the bottom of the loop's process box and points back up to before the loop's input box, controlled by a counter.)*


Pseudocode:

DECLARE TotalScore : INTEGER

DECLARE PlayerScore : INTEGER

DECLARE AverageScore : REAL

DECLARE Counter : INTEGER


TotalScore = 0 // Initialisation is critical!


FOR Counter = 1 TO 11

OUTPUT "Enter score for player ", Counter, ":"

INPUT PlayerScore

TotalScore = TotalScore + PlayerScore

NEXT Counter


AverageScore = TotalScore / 11


OUTPUT "The team's average score is: ", AverageScore


**5. Visual Mental Models**


To truly internalise these concepts, use these mental pictures.


* Algorithm as a Recipe: Think of an algorithm as a recipe for a dish like Chicken Biryani. Each step is an instruction (`Process`). The ingredients are the `INPUT`. The final Biryani is the `OUTPUT`. If any step is ambiguous ("cook for a while") or out of order, the result will be a disaster.


* Selection (IF-THEN-ELSE) as a Fork in the Road:

Imagine you are walking down a path. You reach a signpost (the `IF` condition).

* The sign asks: "Is it raining?"

* If YES, you take the path on the left leading to a shelter (`THEN` block).

* If NO, you take the path on the right leading to the park (`ELSE` block).

Crucially, you can only take one path. Both paths eventually meet up again to continue the journey.


|

V

(Is it raining?)

/ \

(YES) (NO)

/ \

V V

(Go to shelter) (Go to park)

\ /

\ /

V V

(Continue journey)

|

V


* Iteration (Loop) as a Racetrack:

* FOR Loop (Count-Controlled): Imagine a runner, Ahmed, who has to run exactly 5 laps around a track. He has a counter. After each lap, he increments his counter. When the counter reaches 5, he stops. He knows the exact number of laps before he starts.

* WHILE Loop (Pre-Condition): Now imagine Ahmed is told, "Keep running WHILE the sun is still up." Before starting each lap, he looks up at the sky (checks the condition). If the sun is up, he runs another lap. If it's already dark when he arrives at the track, he doesn't run at all. The loop might not execute even once.

* REPEAT...UNTIL Loop (Post-Condition): Now the instruction is, "Run laps REPEATedly UNTIL you are tired." Ahmed runs one lap first (the code block executes once). *Then*, at the end of the lap, he asks himself, "Am I tired?" (checks the condition). If not, he runs another. He is guaranteed to run at least one lap, even if he was tired to begin with.


**6. Common Mistakes & Misconceptions**


Many students lose marks not because they don't know the topic, but because of small, recurring errors. Be vigilant about these.


  1. Mistake: Mixing up Flowchart Symbols.

* *Error:* Using a rectangle (Process) for `INPUT` or `OUTPUT`.

* *Why it's wrong:* Each symbol has a strict, universally understood meaning. Using the wrong symbol makes the flowchart logically incorrect and hard to read. A rectangle is for internal data manipulation, while a parallelogram is for communication with the outside world.

* *Correct Thinking:* Always remember: Parallelograms let the data flow (in or out). Rectangles do the work.


  1. Mistake: Forgetting to Initialise Variables.

* *Error:* In the cricket example, forgetting the line `TotalScore = 0` before the loop.

* *Why it's wrong:* A variable in a computer's memory, before you assign a value to it, contains random garbage data. If you start with `TotalScore = ` and then add to it, your final total will be completely wrong.

* *Correct Thinking:* Any variable that is used to accumulate a total (a sum, a count) must be set to zero before the accumulation process begins.


  1. Mistake: Creating an Infinite Loop.

* *Error:* `Counter = 1`

`WHILE Counter > 0 DO`

` OUTPUT "Hello"`

`ENDWHILE`

* *Why it's wrong:* The value of `Counter` is never changed inside the loop. It will always be 1, so the condition `Counter > 0` will always be true, and the loop will never end. This violates the "finiteness" property of an algorithm.

* *Correct Thinking:* Inside any condition-controlled loop (`WHILE` or `REPEAT`), there must be a statement that can eventually change the condition to make it false (or true for `UNTIL`).


  1. Mistake: "Off-by-One" Error in FOR Loops.

* *Error:* Wanting to process 10 items and writing `FOR Counter = 1 TO 9`. This loop only runs 9 times. Or wanting to access array elements 0 to 9 and writing `FOR i = 1 to 10`.

* *Why it's wrong:* The loop counter in a `FOR...TO...NEXT` loop is inclusive. `FOR i = 1 TO 10` runs for i=1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.

* *Correct Thinking:* Always double-check your loop boundaries. Mentally (or on paper) trace the first and last values to ensure they are correct.


  1. Mistake: Vague or Ambiguous Pseudocode.

* *Error:* Writing statements like `Calculate bill` or `Find the largest number`.

* *Why it's wrong:* This is not an instruction. It describes a goal, but not the steps to achieve it. Pseudocode must be composed of simple, executable steps (assignments, inputs, outputs, conditions).

* *Correct Thinking:* Break it down further. Instead of `Calculate bill`, write `Bill = Units * Rate`. Instead of `Find the largest number`, write the loop and `IF` statement required to compare numbers.


  1. Mistake: Incorrectly Nested Logic.

* *Error:* Placing an `ENDIF` or `NEXT` in the wrong place when you have loops inside `IF` statements, or vice versa.

* *Why it's wrong:* The logical structure of the program is destroyed. An `IF` statement must be fully contained within a loop, or a loop must be fully contained within one branch of an `IF` statement. They cannot overlap improperly.

* *Correct Thinking:* Use indentation in your pseudocode religiously. It visually shows the structure and helps you see which `ENDIF` belongs to which `IF`, and which `NEXT` belongs to which `FOR`.


**7. Exam Technique & Mark Scheme Tips**


Listen closely. This is how you convert your knowledge into marks. Cambridge examiners are precise, and you must be too.


* Command Words are King:

* "Write an algorithm...": This gives you a choice. You can provide a flowchart OR pseudocode. Choose the one you are more comfortable and faster with. For most complex problems, pseudocode is quicker to write.

* "Describe...": This requires an English explanation, not a diagram or code. For example, "Describe the purpose of a `WHILE` loop."

* "Explain...": This requires more detail than "Describe." You need to provide reasons and examples. "Explain the difference between a `WHILE` loop and a `REPEAT...UNTIL` loop."

* "Trace..." or "Complete the trace table...": This is a dry run. You must execute the algorithm on paper, step-by-step, showing how the values of variables change. Be meticulous. One small calculation error can derail the whole table.


* How Marks are Awarded for Algorithms:

* Logic over Syntax: Examiners are looking for the correct logical flow. A small mistake like writing `PRINT` instead of `OUTPUT` will likely not be penalised. But a logical error, like putting a process in the wrong place or using `<` instead of `>`, will lose you marks.

* Key Elements: Marks are typically awarded for specific "checkpoints" in your algorithm. For example, in the cricket average problem:

* 1 mark for correctly initialising `TotalScore` to 0.

* 1 mark for a loop that correctly iterates 11 times.

* 1 mark for correctly inputting a score inside the loop.

* 1 mark for correctly accumulating the total inside the loop (`TotalScore = TotalScore + PlayerScore`).

* 1 mark for correctly calculating the average *after* the loop.

* 1 mark for correctly outputting the final average.

* This means even if you make a mistake, you can still get most of the marks if the rest of your structure is sound. Never leave a question blank. Write down what you know.


* Examiner Traps:

* Data Types: Be careful with `INTEGER` vs `REAL`. If you are calculating an average, the result is often a decimal, so the variable holding it should be `REAL`.

* Edge Cases: When testing your logic, think about the boundaries. What if the user inputs 0? Or a negative number? Or for the WAPDA example, what if they input exactly 200? Your `IF Units <= 200` correctly handles this. `IF Units < 200` would be wrong.

* Clarity is Crucial: Use meaningful variable names. `StudentMarks` is infinitely better than `x`. It makes your algorithm easier for the examiner to understand (and for you to debug).


**8. Memory Tricks & Mnemonics**


* Flowchart Symbols Mnemonic:

Remember this little rhyme:

> Ovals start and stop the show,

> Parallelograms let the data flow.

> Rectangles do the work, you know,

> And Diamonds ask which way to go.


* Loop Types: WHEN to check?

* WHILE: "While you're at the door, check the password." (Checks before entering the loop).

* REPEAT...UNTIL: "Repeat the work until the job is done." (Does the work before checking if it's finished).


* Pseudocode Structure:

Think of the keywords as "sandwich bread."

* `IF` needs an `ENDIF`.

* `CASE` needs an `ENDCASE`.

* `FOR` needs a `NEXT`.

* `WHILE` needs an `ENDWHILE`.

* `REPEAT` needs an `UNTIL`.

Every time you write the opening keyword, get into the habit of immediately writing the closing keyword a few lines below, then filling in the middle. This prevents nesting errors.


**9. Pakistan & Everyday Connections**


This isn't just a theoretical subject. You interact with algorithms every single day in Pakistan.


  1. EasyPaisa/JazzCash App: When you transfer money, you are executing an algorithm.

* `START` -> `INPUT RecipientNumber` -> `INPUT Amount` -> `PROCESS ValidateSufficientBalance` -> `DECISION: Is Balance > Amount?` -> (Yes) -> `INPUT PIN` -> `DECISION: Is PIN correct?` -> (Yes) -> `PROCESS DeductAmount` -> `PROCESS CreditRecipient` -> `OUTPUT "Transaction Successful"` -> `END`. This combines sequence, selection, and processes.


  1. NADRA's Database System: When a government official searches for your family record using your CNIC, the system doesn't check all 220 million Pakistanis one by one. It uses a highly efficient searching algorithm (like a binary search, which you will learn about) to find your record in a fraction of a second. The algorithm repeatedly divides the search area in half until it pinpoints the correct record.

  1. Traffic Signals in Lahore or Karachi: Modern traffic control systems use algorithms to manage traffic flow. They take inputs (data from sensors under the road that count cars), process this data, and make decisions (`IF` traffic is heavy on Shahrah-e-Faisal, `THEN` increase green light duration). This is a real-time problem-solving algorithm at work.

**10. Practice Problems**


Now, test your understanding. Try to design an algorithm (pseudocode is preferred) for each of these.


  1. Bookwork: Write an algorithm that takes two numbers from a user, and then outputs the larger of the two numbers.

* *Answer Outline:* Input Num1, Input Num2. Use an `IF Num1 > Num2 THEN OUTPUT Num1 ELSE OUTPUT Num2 ENDIF`.


  1. Calculation: A shop in a bazaar gives a 10% discount if the total purchase amount is over Rs. 5000. Write an algorithm that takes the total amount as input and outputs the final price to be paid.

* *Answer Outline:* Input Amount. `IF Amount > 5000 THEN FinalPrice = Amount * 0.9 ELSE FinalPrice = Amount ENDIF`. Output FinalPrice.


  1. Application (Iteration): Write an algorithm that asks the user to enter 10 numbers and then calculates and displays the sum of only the positive numbers entered.

* *Answer Outline:* Initialise `Total = 0`. Start a `FOR` loop from 1 to 10. Inside the loop, `INPUT Number`. Use an `IF Number > 0 THEN Total = Total + Number ENDIF`. After the loop, `OUTPUT Total`.


  1. Challenging Application (Combining Constructs): PTCL offers an internet package where the first 50 GB of data costs Rs. 2000. Any data used above 50 GB is charged at Rs. 50 per GB. Write an algorithm that takes the total GB used as input and calculates the monthly bill.

* *Answer Outline:* Input `GB_Used`. `IF GB_Used <= 50 THEN Bill = 2000 ELSE Extra_GB = GB_Used - 50; Bill = 2000 + (Extra_GB * 50) ENDIF`. Output `Bill`.


  1. Advanced Logic: Write an algorithm that keeps asking a user to enter a password until they enter the correct one, which is "Pakistan123". The algorithm should also count and display how many wrong attempts they made.

* *Answer Outline:* Initialise `Attempts = 0`. `DECLARE Password : STRING`. `REPEAT INPUT Password; IF Password <> "Pakistan123" THEN Attempts = Attempts + 1 ENDIF UNTIL Password = "Pakistan123"`. Output "Access granted." and "Wrong attempts: ", `Attempts`. (A `WHILE` loop could also be used here).


Master these fundamentals, and you will have the tools to solve any problem the Cambridge examiners can throw at you. Good luck.

Key Points to Remember

  • 1An algorithm is a logical, step-by-step set of instructions designed to solve a specific problem.
  • 2Decomposition is the process of breaking down a complex problem into smaller, more manageable sub-problems.
  • 3Abstraction is the process of ignoring unnecessary details in a problem to focus only on the essential characteristics.
  • 4Flowcharts and pseudocode are tools used to design and refine the logic of an algorithm before writing program code.
  • 5An algorithm must have the property of finiteness, meaning it must terminate after a finite number of steps.
  • 6An algorithm must be definite, meaning each step must be precisely and unambiguously defined with no room for interpretation.
  • 7An algorithm is independent of any specific programming language; it is a logical plan that can be implemented in various languages.
  • 8A computer is a tool that follows an algorithm's instructions precisely and cannot interpret ambiguous commands.
  • 9An infinite loop is a common programming error where an algorithm fails to terminate, thus violating the property of finiteness.
  • 10Designing a clear and logical algorithm is a crucial planning stage that must be completed before implementation in a programming language.

Pakistan Example

Finding the Shortest Rickshaw Route

Imagine you're in Saddar, Karachi, and need to find the cheapest rickshaw to Clifton. You could use a linear search: ask each rickshaw wala his fare (150, 200, 120, 180, 130) and keep track of the minimum. In pseudocode: min = 999, FOR each fare: IF fare < min THEN min = fare. Result: 120. Google Maps uses much more complex algorithms (Dijkstra's algorithm) to find the shortest route, considering distance, traffic, and road conditions. But the basic logic is the same — compare and track the best option!

Quick Revision Infographic

Computer Science — Quick Revision

Algorithms & Programming

Key Concepts

1An algorithm is a logical, step-by-step set of instructions designed to solve a specific problem.
2Decomposition is the process of breaking down a complex problem into smaller, more manageable sub-problems.
3Abstraction is the process of ignoring unnecessary details in a problem to focus only on the essential characteristics.
4Flowcharts and pseudocode are tools used to design and refine the logic of an algorithm before writing program code.
5An algorithm must have the property of finiteness, meaning it must terminate after a finite number of steps.
6An algorithm must be definite, meaning each step must be precisely and unambiguously defined with no room for interpretation.
Pakistan Example

Finding the Shortest Rickshaw Route

Imagine you're in Saddar, Karachi, and need to find the cheapest rickshaw to Clifton. You could use a linear search: ask each rickshaw wala his fare (150, 200, 120, 180, 130) and keep track of the minimum. In pseudocode: min = 999, FOR each fare: IF fare < min THEN min = fare. Result: 120. Google Maps uses much more complex algorithms (Dijkstra's algorithm) to find the shortest route, considering distance, traffic, and road conditions. But the basic logic is the same — compare and track the best option!

SeekhoAsaan.com — Free RevisionAlgorithms & Programming Infographic

Test Your Knowledge!

10 Beginner10 Intermediate10 Advanced
Start 30-Question Quiz