←
Class 11 Computer Science
4. Introduction to Problem Solving · 4 / 11
⌕
Chapter 4 of 11

4. Introduction to Problem Solving

11 sections · 6,107 words

About this chapter

192 words · 1 min read

Big idea: Plan the steps on paper. Then type the program. Then test it.

This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.

  • Follow the cycle: analyse, algorithm, code, and test.
  • Tell an algorithm from a program. Name the six properties.
  • Draw flowchart shapes. Write matching pseudocode.
  • Use sequence, selection, and repetition.
  • Dry-run steps in a trace table. Test normal and edge cases.
  • Compare two plans by counting steps and memory.
  • Name syntax, runtime, and logic errors. Use comments.
  • Split a big job. Reuse patterns. Hide extra detail.

The word algorithm comes from the scholar al-Khwarizmi. He lived in the ninth century. He wrote step-by-step arithmetic methods. In 1843, Ada Lovelace published a machine plan. It computed Bernoulli numbers. The machine was Charles Babbage's Analytical Engine. In 1936, Alan Turing described a model of a computer. It followed steps one by one. These ideas still sit under every program.

4.1 Steps for problem solving

598 words · 3 min read

A computer follows a plan. The plan comes from you.

A computer is fast. It is not wise. It only follows steps.

Wrong steps give wrong answers. That rule is GIGO.

GIGO means garbage in, garbage out.

Do not start at the keyboard. Think first. Then type.

The problem-solving cycle has four stages.

1. Analyse: name inputs, outputs, rules2. Algorithm: write clear steps3. Code: type the steps in a language4. Test: run cases and fix faults
Problem-solving cycle. Analyse, plan, code, then test.

How to read the figure. Start at the top. Analyse first. Then write the algorithm. Then code. Then test. A fault sends you back.

Analyse before you type. Test after you type.

This cycle is the exam model. Name the four stages in order.

Input is the data that goes in.

Output is the result that must come out.

Processing is the rule that turns input into output.

Ask three questions. What goes in? What comes out? What is the rule?

If you skip this, you may solve the wrong job.

An algorithm is a finite list of clear steps.

Write it in plain words. Or draw it. Do not need a language yet.

Coding turns the plan into a language the machine can run.

Python is one such language. Spelling must be exact.

Run the program with several inputs. Check the output.

Debugging means find the fault. Then fix it.

Test small parts first. Then test them together. Then test the whole job.

Maintenance is later work. Fix faults. Add features.

The cycle is not a one-way street. A test fault can send you back to analyse.

A coding fault can send you back to the algorithm. That is normal.

Write the analysis down. List inputs. List outputs. List rules.

That short list is the first piece of documentation. Keep it with the plan.

If two people read the list, they should name the same output.

That expected output is later used as a test check. If the program prints something else, it failed.

Keep one small example with the analysis. The sports-club case below is that kind of example.

  • GIGO: bad input or bad steps give a bad result.
  • Algorithm: a finite list of clear steps for a job.
  • Debugging: finding and fixing faults in a program.
  • Maintenance: work after the first release.

A club gives 3 points for a win, 1 for a draw, and 0 for a loss. A team has 5 wins, 2 draws, and 1 loss. Name input, process, and output.

Goal. Name input, process, and output.

Rule. Input is given data. Process is the formula. Output is the total.

Input. Wins 5, draws 2, losses 1.

Process. Multiply wins by 3. Multiply draws by 1. Add them.

Arithmetic. 5 × 3 = 15. 2 × 1 = 2. 1 × 0 = 0.

Add. 15 + 2 + 0 = 17.

Result: Input is the match counts. Output is 17 points.

Cover the answers. Try each item on paper first.

Watch out: Do not type first. Name the input and the output first.

⚡ Quick Check Flashcards4 questions
Question 1
What do the letters in GIGO stand for?
Try answering before revealing!
Question 2
Name the four stages in order.
Try answering before revealing!
Question 3
What is the difference between input and output?
Try answering before revealing!
Question 4
What is debugging?
Try answering before revealing!

4.2 Algorithms and their properties

586 words · 3 min read

An algorithm is a recipe. It always ends.

A recipe lists steps in order. Skip one step and the dish fails.

An algorithm is the same idea for a computer.

It takes input. It does clear work. It gives output. It stops.

Write the algorithm before the program. Check the logic first.

QuestionAlgorithmProgram
What is it?A plan in plain stepsTyped instructions
Who reads it?PeopleA computer
Language?Any words or a diagramOne strict language
Can it run?No. It is a planYes, after translation
If a step is vague?Fix the wordsThe machine cannot guess

How to read the table. Stay on one row. Compare the two columns. An algorithm is not code.

A program is an algorithm written in a language a machine can run.

The same algorithm can become Python, Java, or C++. The plan does not change.

  • It does not lock you to one language.
  • You can check the logic before typing.
  • A teammate can read the plan.
  • Missing steps show up early.

If two algorithms give the same output for every valid input, they are both correct.

They may still differ in speed. Section 4.6 compares that.

A true algorithm must pass six tests.

PropertyWhat it means
FinitenessIt stops after a finite number of steps.
DefinitenessEach step has one clear meaning.
InputIt takes zero or more known inputs.
OutputIt gives at least one known output.
EffectivenessA person could do each step on paper.
UniquenessThe next result follows only from known values.

How to read the table. Finiteness is the stop rule. Definiteness is the one-meaning rule.

A loop that never ends fails finiteness. That list is not an algorithm.

A vague step fails definiteness. "Heat until done" is vague.

"Heat for 10 minutes at 180 degrees" is definite.

A step that needs magic fails effectiveness. "Guess the password" is not a step you can carry out.

"Try each 4-digit code from 0000 to 9999" is finite, definite, and effective. It may be slow. It is still an algorithm.

  • Finiteness: the plan must stop.
  • Definiteness: each step has one meaning.
  • Effectiveness: each step can be done in practice.

Find the GCD of 36 and 48 by listing common divisors. Then check with remainders.

Goal. Find the greatest common divisor of 36 and 48.

Rule. The GCD is the largest number that divides both.

List. Divisors of 36: 1, 2, 3, 4, 6, 9, 12, 18, 36.

List. Divisors of 48: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48.

Common. 1, 2, 3, 4, 6, 12. The largest is 12.

Check. 48 = 36 × 1 + 12. Then 36 = 12 × 3 + 0. Stop. GCD is 12.

Result: The GCD is 12. The steps are finite and unique.

Pause here. Answer before you scroll to the answers.

Watch out: An algorithm is not a program. It is the plan you write first.

⚡ Quick Check Flashcards4 questions
Question 1
What happens if finiteness fails?
Try answering before revealing!
Question 2
Why is an algorithm independent of a language?
Try answering before revealing!
Question 3
What is definiteness?
Try answering before revealing!
Question 4
Can an algorithm have zero inputs?
Try answering before revealing!

4.3 Representation of algorithms: flowcharts and pseudocode

658 words · 3 min read

Show the plan as a picture or as structured text.

Record the steps before you code. Draw them. Or write them.

A flowchart is a diagram of the plan. Shapes have fixed jobs.

Pseudocode is structured text. It looks a bit like code. It is for people.

Start / StopTerminatorBegin or endInput / OutputData in or outRead A, Print SProcessA calculationsum = sum + nDecideTrue or falseYes and No pathsCFlowlineCircle joins paths
Flowchart symbol key. Each shape has one job.

How to read the figure. Match each shape to its job. Rounded box starts or stops. Parallelogram moves data. Rectangle calculates. Diamond asks a yes-or-no question. The arrow shows direction.

Here is a full flowchart. It prints the larger of A and B.

StartInput A and BA B ?YesPrint ANoPrint BStop
Decision flowchart. One test splits into two paths that meet at Stop.

How to read the figure. Start at the top. Enter A and B. At the diamond, go left if A is larger. Go right if not. Both paths meet at Stop.

A machine cannot run a flowchart. The drawing is a design tool.

A flowchart has one Start. It has at least one Stop.

Arrows leave a diamond on two labelled paths. Label them Yes and No.

Do not cross arrows if you can join them with a small circle.

Keep one idea in each box. "Add 1 and print and stop" is too much for one box.

Pseudocode has loose spelling. Common keywords still help.

KeywordJobExample
INPUTTake a valueINPUT score
SET or COMPUTEStore a valueSET area = length * width
PRINTShow a resultPRINT area
IF ... THEN ... ELSEChoose a pathIF age >= 18 THEN PRINT "Adult"
WHILE ... REPEATRepeat while trueWHILE count < 5 REPEAT

How to read the table. The left column is the word. The middle column is the job. Copy the pattern on the right.

PseudocodePython
INPUT lengthlength = 18
COMPUTE area = length * widtharea = length * width
PRINT areaprint(area)
IF a > b THEN PRINT aif a > b: print(a)

How to read the table. Each row is the same idea. The right column is real Python. Indent after a colon.

Pseudocode is the plan. Python is the typed form of that plan.

Python
length = 18
width = 12
area = length * width
perim = 2 * (length + width)
print(area)
print(perim)

Output
216
60

The printout is 216 then 60. That matches the arithmetic in the worked example.

  • Flowchart: a diagram of steps using standard shapes.
  • Pseudocode: a plain-text outline of the steps.
  • Terminator: the rounded start or stop box.

Write pseudocode for a rectangle of length 18 and width 12. Find area and perimeter.

Goal. Find area and perimeter.

Rule. Area is length times width. Perimeter is twice the sum of the sides.

INPUT length

INPUT width

COMPUTE area = length * width

COMPUTE perim = 2 * (length + width)

PRINT area

PRINT perim

Arithmetic. 18 × 12 = 216. 18 + 12 = 30. 2 × 30 = 60.

Result: Area is 216 square units. Perimeter is 60 units.

Output
INPUT length
INPUT width
COMPUTE area = length * width
COMPUTE perim = 2 * (length + width)
PRINT area
PRINT perim

Test yourself on these. Then read the explained answers.

Watch out: A computer cannot run pseudocode. Translate it into a real language first.

⚡ Quick Check Flashcards4 questions
Question 1
Which shape is used for input and output?
Try answering before revealing!
Question 2
Which shape is used for a decision?
Try answering before revealing!
Question 3
What does pseudo mean here?
Try answering before revealing!
Question 4
Why write pseudocode before Python?
Try answering before revealing!

4.4 Flow of control: sequence, selection and repetition

589 words · 3 min read

Control is the order of the steps.

Steps do not always run in a straight line.

A test can skip a block. A loop can repeat a block.

Three structures build every plan. Sequence. Selection. Repetition.

In a sequence, each step runs once. Top to bottom. No skip. No repeat.

Read two numbers. Add them. Print the sum. That is a sequence.

Selection chooses a path. The test is a condition.

A condition is True or False. Those two values are Boolean.

  • One branch: do the work only if the test is True.
  • Two branches: one path if True, the other if False.
  • Many branches: test several conditions in order.
Output
INPUT age
IF age < 13 THEN
    PRINT "Child fare"
ELSE IF age < 60 THEN
    PRINT "Standard fare"
ELSE
    PRINT "Senior fare"

Here is the same idea in Python. A is 9. B is 4.

Python
a = 9
b = 4
if a > b:
    print(a)
else:
    print(b)

Output
9

Repetition is a loop. Another name is iteration.

  • Counted loop: you know how many times to repeat.
  • Conditional loop: repeat while a test stays True.
Startsum=0, count=1count = 5?Yessum = sum + countcount = count + 1NoPrint sumStop
Loop flowchart. The left arrow repeats until the test is false.

How to read the figure. Start at the top. Set sum to 0 and count to 1. At the diamond, Yes goes down. Add count to sum. Add 1 to count. The left arrow goes back. No goes right and prints the sum.

A loop needs an update. If count never changes, the loop never ends.

The three structures are enough. Complex jobs are just these three, nested.

You can nest them. A loop can hold a selection. A selection can hold a sequence.

Indent nested steps. The indent shows what sits inside the test or the loop.

The Python loop below is the same running-total pattern as the flowchart.

Python
total = 0
count = 1
while count <= 5:
    total = total + count
    count = count + 1
print(total)

Output
15

Read the printed 15. It must match 1 + 2 + 3 + 4 + 5.

If the print is 10, the stop test was too strict. If the print is 21, the loop went one step too far.

  • Flow of control: the order in which steps run.
  • Sequence: steps in order, once each.
  • Selection: choose a path with a True or False test.
  • Repetition: repeat a block. Also called a loop.

Add the scores 14, 18, 12, 16, and 20. Then find the average.

Goal. Find the sum and the average of five scores.

Rule. Average is sum divided by count.

Start. sum = 0.

Add. 0 + 14 = 14. Then + 18 = 32. Then + 12 = 44.

Add. Then + 16 = 60. Then + 20 = 80.

Divide. 80 ÷ 5 = 16.

Check. 16 × 5 = 80.

Result: Sum is 80. Average is 16.

Write a short answer. Then check the notes below.

Watch out: A loop must change the test variable. Else it never stops.

⚡ Quick Check Flashcards4 questions
Question 1
Name the three control structures.
Try answering before revealing!
Question 2
What two values can a condition have?
Try answering before revealing!
Question 3
What is another name for repetition?
Try answering before revealing!
Question 4
What happens if a loop never meets its stop test?
Try answering before revealing!

4.5 Verifying algorithms and dry runs

673 words · 3 min read

A dry run is a paper test of the steps.

A wrong plan can still become tidy code. The machine will follow the fault.

Check the plan on paper first. That check is a dry run.

Another name is desk checking. You act as the computer.

Pick sample input. Follow each line. Write every new value.

Record the values in a trace table.

Columns hold the step, the test, each variable, and any print.

Start with sum = 0 and count = 1. Repeat while count is at most 4.

Stepcountcount <= 4sumAction
Start1True0Set sum = 0, count = 1
Loop 11True1sum = 0 + 1 = 1. count becomes 2
Loop 22True3sum = 1 + 2 = 3. count becomes 3
Loop 33True6sum = 3 + 3 = 6. count becomes 4
Loop 44True10sum = 6 + 4 = 10. count becomes 5
Exit5False10Print 10

How to read the table. Read one row at a time. Watch count grow. Watch sum grow. The last True row uses count 4.

The printed sum is 10. That matches 1 + 2 + 3 + 4.

A dry run finds logic faults before you type. It cannot find a typing fault in later code.

Testing means run chosen cases and check the output.

  • Normal case: typical values in the middle of the range.
  • Boundary case: a value on the edge, such as 0 or the cutoff.
  • Error case: a value the plan should reject.

Here is a weak time-add plan. It forgets the 60-minute carry.

Output
INPUT h1, m1
INPUT h2, m2
COMPUTE total_h = h1 + h2
COMPUTE total_m = m1 + m2
PRINT total_h, total_m

A normal case looks fine. 2 h 15 min plus 1 h 20 min prints 3 h 35 min.

A boundary case fails. 2 h 45 min plus 1 h 35 min prints 3 h 80 min.

That is wrong. 80 minutes is more than one hour.

Write the cases you ran. That list is test documentation.

A later change can reuse the same cases. That saves time.

How to dry-run, in order:

  • Pick one input set. Write it at the top of the page.
  • Make a column for each variable.
  • Follow one instruction. Update only the changed column.
  • When a PRINT runs, write the value in an output column.
  • At the end, compare the output with a hand calculation.
Output
IF total_m >= 60 THEN
    total_h = total_h + 1
    total_m = total_m - 60

  • Dry run: follow the steps on paper with sample input.
  • Trace table: a table of variable values after each step.
  • Boundary: an input on the edge of a range.

Dry-run 2 hours 45 minutes plus 1 hour 35 minutes with the carry fix.

Goal. Add the two times with a 60-minute carry.

Rule. If minutes are 60 or more, add 1 hour and subtract 60 minutes.

Hours. 2 + 1 = 3.

Minutes. 45 + 35 = 80.

Test. Is 80 >= 60? Yes.

Carry. Hours become 3 + 1 = 4.

Reduce. Minutes become 80 - 60 = 20.

Check. 4 hours 20 minutes = 260 minutes. 2×60+45 + 1×60+35 = 260.

Result: The time is 4 hours and 20 minutes.

Cover the answers. Try each item on paper first.

Watch out: Do not test only typical values. Also test 0, the cutoff, and a rejected value.

⚡ Quick Check Flashcards4 questions
Question 1
What is the main use of a dry run?
Try answering before revealing!
Question 2
What belongs in a trace table?
Try answering before revealing!
Question 3
Why did the first time-add plan fail at 45 and 35 minutes?
Try answering before revealing!
Question 4
Name three kinds of test case.
Try answering before revealing!

4.6 Comparing algorithms

633 words · 3 min read

One job can have many plans. Count the work.

Two plans can solve the same job. One may be cheaper.

Do not judge a plan by how short the text looks.

Judge efficiency. Count operations. Count extra memory.

Time complexity is how the step count grows as N grows.

Space complexity is extra memory used while the plan runs.

Plan A uses a loop. It adds 1, then 2, then each next whole number.

That is N additions. For N = 100, that is 100 additions.

Plan B uses a formula. Sum = N × (N + 1) / 2.

That is one add, one multiply, and one divide. Three operations for any N.

Step count versus N. The loop grows. The formula stays flat.

How to read the figure. The horizontal axis is N. The rising line is the loop. The flat line is the formula. At N = 100 the loop is far above 3.

For N = 100, Plan B gives (100 × 101) / 2 = 5050.

Fewer operations mean a faster plan. Line count on paper is not speed.

A formula is not always available. Then a clear loop is still a good plan.

A prime number is an integer greater than 1. Its only positive divisors are 1 and itself.

ApproachWhat you testTests for N = 101
All integers2 up to N − 199 divisions
Up to half2 up to N / 250 divisions
Up to square root2 up to sqrt(N)9 divisions (2 through 10)
Primes to square rootprimes up to sqrt(N)4 divisions (2, 3, 5, 7)

How to read the table. Each row cuts the work. Square of 10 is 100. So 101 needs tests only to 10. That is 9 tests, not 99.

The last row uses extra memory. You must store a list of primes. That is a space cost.

Time and space often trade. A list of primes saves tests. It uses RAM.

For a one-off check of 101, extra storage is not worth it. For many checks, it can be.

Always name N. "Fast" means nothing until you say how the cost grows with N.

A simple count: if a loop runs from 1 to N, the body runs N times.

If that body has 2 additions, the loop costs about 2N additions.

The formula still costs 3. For large N, 3 beats 2N.

  • Time complexity: how the number of operations grows with N.
  • Space complexity: how much extra memory the plan uses.
  • Efficiency: enough speed and memory for the job.

Count the additions to sum 1 to 50 with a loop. Then with the formula.

Goal. Compare step counts for the same sum.

Loop. Add 50 numbers. That is 50 additions.

Formula. (50 × 51) / 2.

Multiply. 50 × 51 = 2550.

Divide. 2550 / 2 = 1275.

Count. Formula uses 1 add, 1 multiply, 1 divide. Three operations.

Result: Both give 1275. The formula uses 3 operations. The loop uses 50.

Pause here. Answer before you scroll to the answers.

Watch out: A short page of text is not always a fast plan. Count the operations that run.

⚡ Quick Check Flashcards4 questions
Question 1
What is time complexity?
Try answering before revealing!
Question 2
What is space complexity?
Try answering before revealing!
Question 3
Why is the sum formula faster than a loop?
Try answering before revealing!
Question 4
Why stop prime tests at the square root?
Try answering before revealing!

4.7 Coding and programming languages

670 words · 3 min read

Coding types the checked plan in a language.

Coding writes the steps in a high-level language. Python is one.

The file you type is source code.

Syntax is the grammar of that language. Spelling counts. Order counts.

A missing bracket is a syntax error. The translator stops.

Hardware understands machine language. That is 0 and 1.

People do not write long strings of 0 and 1. A high-level language uses words and maths signs.

High-level code is portable. The same file can run on more than one machine.

TranslatorHow it worksWhen errors show
CompilerTranslates the whole file first. Makes a separate runnable file.Lists syntax faults after a full scan.
InterpreterTranslates and runs one line at a time.Stops at the first line with a fault.

How to read the table. A compiler waits. An interpreter runs as it reads. Python usually uses an interpreter.

Documentation explains the code to the next reader. That reader may be you later.

  • A comment states why a step exists.
  • A clear name states what a value holds.
  • A short header states input, output, and the rule.

Comments do not change the result. They change how safe the file is to edit.

Choose names that state the job. total is clearer than x.

Do not comment what the line already says. Comment the reason.

  • Desktop programs run on a laptop or a classroom PC.
  • Web programs run on a server and show pages in a browser.
  • Mobile programs run on a phone or a tablet.
  • An embedded system is a small computer inside a machine. A microwave is one. A car lock is another.

KindWhen you see itExample
SyntaxBefore a run, or at the first bad linePRNT instead of print
RuntimeWhile the program is runningDivide by zero
LogicThe program finishes, but the answer is wrongAdd when you should multiply

How to read the table. Syntax is a language fault. Runtime is a crash. Logic is a quiet wrong answer.

A program with no syntax errors can still be wrong.

The machine follows your logic exactly. A logic fault is your plan, not the translator.
Python
# running total of 1 to 5
total = 0
count = 1
while count <= 5:  # stop after 5
    total = total + count
    count = count + 1
print(total)

Output
15

The comments did not change the printout. They tell the reader why the loop stops.

  • Source code: the typed program in a high-level language.
  • Syntax: the grammar rules of the language.
  • Compiler: translates the whole file before a run.
  • Interpreter: translates and runs line by line.
  • Documentation: comments and names that explain the code.
  • Embedded system: a small computer built into a larger machine.

A rectangle-area program has three faults. (1) PRNT instead of PRINT. (2) Divide by zero. (3) area = length + width. Name each error kind.

Goal. Classify each fault.

Rule. Syntax breaks language rules. Runtime crashes during a run. Logic finishes with the wrong value.

Case 1. PRNT is not a keyword. Syntax error.

Case 2. Divide by zero stops the run. Runtime error.

Case 3. The program runs. The area is wrong. Logic error.

Result: Case 1 syntax. Case 2 runtime. Case 3 logic.

Test yourself on these. Then read the explained answers.

Watch out: Zero syntax errors is not enough. A logic error still prints a wrong answer.

⚡ Quick Check Flashcards4 questions
Question 1
What is source code?
Try answering before revealing!
Question 2
What happens if syntax is broken?
Try answering before revealing!
Question 3
What is the main difference between a compiler and an interpreter?
Try answering before revealing!
Question 4
Why write comments?
Try answering before revealing!

4.8 Problem decomposition

649 words · 3 min read

Split a large job. Solve each part. Then join the parts.

A huge job is hard to hold in one view. Split it.

Decomposition means break one job into smaller jobs.

Another name is divide and conquer.

Solve each part. Then connect the parts.

School library systemMembersCatalogIssueFinesSolve each box on its own.Then join the four parts.Name each box input and output.
Decomposition tree. One system splits into four smaller jobs.

How to read the figure. The top box is the whole system. The four lower boxes are parts. Members, catalog, issue, and fines. Each part has its own input and output.

  • Each part is small enough to understand.
  • Different people can work on different parts.
  • You can test one part before you join it.
  • A solved part can be reused later.

A pattern is a plan you have seen before. Reuse it. Do not invent from zero.

PatternWhat it does
Running totalStart at 0. Add each next value.
Find the largestKeep a champion. Replace it when a bigger value arrives.
Count matchesStart at 0. Add 1 when a test is True.
Guard a rangeReject a value below a min or above a max.

How to read the table. Match the job to a row. The loop in 4.4 is a running total.

Abstraction means hide extra detail. Show only what this stage needs.

LayerWhat you seeWhat is hidden
UserA button labelled BorrowThe files and the loop
AlgorithmIssue a book if it is in stockPython syntax
Codeif copies > 0: copies = copies - 1CPU instructions
Machine0s and 1s moving in hardwareThe library story

How to read the table. Go down one row. Each row hides the row below. You work at one layer at a time.

Name each part. Hide the rest until you need it.

Decomposition splits width. Abstraction splits depth. Use both on a large system.

Write the join contract. Part 1 output must match Part 2 input.

If Part 1 sends a percent and Part 2 expects a yes-or-no flag, the join fails.

Test each part with its own cases. Then test the chain.

A pattern plus a split plus a hidden layer is how large software is built.

Everyday splits look the same. A sports day splits into events, scores, kit, and awards.

A weather app splits into data in, a forecast, a map, and an alert.

Name the pattern you reuse. "This is a running total" helps a teammate read the loop.

  • Decomposition: split one job into smaller jobs.
  • Pattern: a reusable plan for a common job.
  • Abstraction: hide detail that the current stage does not need.
  • Module: one self-contained part of a larger system.

Split an automatic plant-watering system into three parts. Name input and output for each part.

Goal. Decompose the system.

Rule. Each part has a clear input and a clear output.

Part 1. Moisture reader. Input: sensor value. Output: moisture percent.

Part 2. Decision. Input: moisture percent. Output: pump ON or OFF.

Part 3. Pump driver. Input: ON or OFF. Output: power to the pump.

Join. Part 1 feeds Part 2. Part 2 feeds Part 3.

Result: Three parts: read moisture, decide, drive the pump.

Write a short answer. Then check the notes below.

Watch out: When you split a job, name each part input and output. Else the parts will not join.

⚡ Quick Check Flashcards4 questions
Question 1
What is decomposition?
Try answering before revealing!
Question 2
Give two gains for a team.
Try answering before revealing!
Question 3
What is a pattern in this chapter?
Try answering before revealing!
Question 4
What does abstraction hide?
Try answering before revealing!

Summary

122 words · 1 min read
  • The cycle is analyse, algorithm, code, then test.
  • GIGO: bad input or bad steps give a bad result.
  • An algorithm is a finite, clear plan. A program is that plan in a language.
  • Six properties: finite, definite, input, output, effective, unique.
  • Flowcharts use standard shapes. Pseudocode uses keywords. Neither runs on its own.
  • Control uses sequence, selection, and repetition.
  • A dry run fills a trace table. Test normal, boundary, and error cases.
  • Compare plans by step count and extra memory, not by line count.
  • Syntax, runtime, and logic errors are different. Comments document the code.
  • Decomposition splits a job. Patterns reuse a known plan. Abstraction hides extra detail.
Explain each important word in your own words. Then say why the rule works.

Exercises

737 words · 3 min read

These questions are new. Show your thinking. For programs, write your answer before you run the code.

4.1 A van travels 90 km in 3 hours. Name input, process, and output for average speed.

4.2 The loop below should print count from 0 to 9. The update is missing. Which property fails, and what happens?

Output
SET count = 0
WHILE count < 10 REPEAT
    PRINT count

4.3 Match each flowchart symbol: (a) parallelogram, (b) diamond, (c) rounded rectangle, (d) rectangle.

4.4 Write pseudocode for a square of side 8. Find area and perimeter.

4.5 A quiz prints Star if score is 80 or more, else Practice. Write IF and ELSE.

4.6 A courier charges 25 up to 4 kg. Each extra kilogram costs 8. Find the charge for 8 kg.

4.7 Dry-run the factorial plan for n = 4. Give product after each loop.

Output
SET product = 1
SET count = 1
WHILE count <= 4 REPEAT
    product = product * count
    count = count + 1
PRINT product

4.8 Write nested IF pseudocode for the largest of A, B, and C.

4.9 The classify plan should print Small or Large. For which input does it print nothing, and how do you fix it?

Output
INPUT number
IF number < 10 THEN
    PRINT "Small"
ELSE IF number > 10 THEN
    PRINT "Large"

4.10 A loop body does 2 additions and runs N times. A formula uses 3 operations. For N = 50, which plan does more work?

4.11 One prime-test plan stores a list of primes. What does it save, and what extra cost does it pay?

4.12 Give one example of (a) syntax error, (b) runtime error, (c) logic error.

4.13 State two differences between a compiler and an interpreter.

4.14 Split a school lunch-order system into four modules.

4.15 Write a sentinel loop. Accept costs until 0. Then print the sum.

4.16 An Armstrong number of three digits equals the sum of the cubes of its digits. Trace 153.

Output
SET n = 153
SET hundreds = 1, tens = 5, units = 3
COMPUTE total = hundreds**3 + tens**3 + units**3
IF total == n THEN PRINT "Armstrong" ELSE PRINT "Not Armstrong"

4.17 A water bill is 4 per unit for the first 80 units. Then 8 per unit for the next 120. Then 15 per unit after that. Add a meter fee of 50. Find the bill for 230 units.

Answers

  1. 4.1: Input is distance 90 km and time 3 hours. Process is 90 ÷ 3. Output is 30 km/h.
  2. 4.2: Finiteness fails. count stays 0, so count < 10 stays True. The loop never stops.
  3. 4.3: (a) parallelogram: input or output. (b) diamond: decision. (c) rounded rectangle: start or stop. (d) rectangle: process.
  4. 4.4: INPUT side. COMPUTE area = side side. COMPUTE perim = 4 side. PRINT area, perim. For side 8, area = 64 and perimeter = 32.
  5. 4.5: INPUT score. IF score >= 80 THEN PRINT "Star" ELSE PRINT "Practice".
  6. 4.6: Extra weight = 8 − 4 = 4 kg. Extra cost = 4 × 8 = 32. Total = 25 + 32 = 57.
  7. 4.7: product starts at 1. After 1: 1. After 2: 2. After 3: 6. After 4: 24. Print 24.
  8. 4.8: INPUT A, B, C. IF A >= B THEN (IF A >= C THEN PRINT A ELSE PRINT C) ELSE (IF B >= C THEN PRINT B ELSE PRINT C).
  9. 4.9: It prints nothing when number is 10. 10 is not less than 10 and not greater than 10. Add an equal case, or use ELSE for the rest.
  10. 4.10: The loop does 2 × 50 = 100 additions. The formula does 3. The loop does more. The loop cost grows with N. The formula cost does not.
  11. 4.11: It saves extra division tests. It pays extra memory. That is a time–space trade.
  12. 4.12: (a) Syntax: PRNT or a missing colon. (b) Runtime: divide by zero. (c) Logic: average = total * count.
  13. 4.13: A compiler translates the whole file and can make a separate runnable file. An interpreter runs line by line and stops at the first fault.
  14. 4.14: 1. Menu display. 2. Item selection. 3. Bill total. 4. Token print.
  15. 4.15: SET sum = 0. INPUT cost. WHILE cost != 0 REPEAT (sum = sum + cost. INPUT cost). PRINT sum.
  16. 4.16: Digits 1, 5, 3. Cubes 1, 125, 27. Sum 1 + 125 + 27 = 153. Equal to 153, so 153 is Armstrong.
  17. 4.17: First 80 × 4 = 320. Next 120 × 8 = 960. Last 30 × 15 = 450. Plus 50. Total 1780.
Up next
Continue to the next chapter