- Learn
- Computer Science & IT
- Computing for Ages 11 to 14
- Flowcharts and Pseudocode
Algorithms with Flowcharts and Pseudocode
Grade 6, Grade 7Lesson 2 of 10 in Computing for Ages 11 to 14 Course
What you will learn
- Explain what an algorithm is, plan one with its inputs, processes and outputs, and use variables to store and change values.
- Plan an algorithm with inputs, processes and outputsRecognize what makes an algorithm precise, plan it with an input–process–output chart, and name the three building blocks that algorithms are built from.
- Store and change values with variablesUse variables, assignment, arithmetic operators, input and output, and tell assigning a value apart from comparing values.
- Plan an algorithm with inputs, processes and outputs
- Read, draw and correct flowcharts that use the standard symbols to show sequence, decisions and loops.
- Use the standard flowchart symbolsRecognize each flowchart symbol and what it means, and follow the rules that make a flowchart clear and complete.
- Show decisions in flowchartsUse decision symbols with comparison operators to choose between paths, including several decisions in a row, decisions inside decisions and combined conditions.
- Show repetition in flowchartsDraw and follow loops in flowcharts, using a counter for a fixed number of repeats or a condition for repeats until something happens.
- Use the standard flowchart symbols
- Write clear, indented pseudocode with input, output, assignment, IF statements, loops and sub-routines, and convert algorithms between pseudocode and flowcharts.
- Write clear, structured pseudocodeFollow consistent pseudocode conventions with keywords, one instruction per line and indentation, and keep every step short, clear and precise.
- Write decisions with IF statementsWrite selection in pseudocode with IF, ELSE and ELSE IF, nest one IF inside another, and combine conditions with AND, OR and NOT.
- Write loops with FOR, WHILE and REPEATWrite count-controlled and condition-controlled loops in pseudocode, choose the right loop for a task, and combine loops with IF statements.
- Convert between flowcharts and pseudocode and use sub-routinesTurn a flowchart into pseudocode and pseudocode into a flowchart, and use named sub-routines to reuse a group of steps.
- Write clear, structured pseudocode
- Follow algorithms step by step with trace tables, predict their output, work out their purpose, and find and fix errors using planned test data.
- Trace an algorithm with a trace tableWork through flowcharts and pseudocode line by line, recording every change of value in a trace table to find exactly what the algorithm does.
- Predict, test and correct algorithmsPredict outputs, work out what an algorithm is for, plan tests with normal, boundary and invalid data, and find and fix logic errors in flowcharts and pseudocode.
- Trace an algorithm with a trace table
- Design algorithms for new problems by combining sequence, selection and iteration, and judge different algorithms for the same task by correctness, efficiency and clarity.
- Design an algorithm for a new problemTurn a problem into a working algorithm by finding its inputs and outputs, choosing the right constructs, writing it as a flowchart or pseudocode, and checking it with test data.
- Compare algorithms that solve the same problemJudge two or more algorithms for the same task by whether they are correct, how many steps they take, how clear they are and which inputs they handle.
- Design an algorithm for a new problem
Flowcharts and Pseudocode study guide
1Describe algorithms precisely
Planning a program begins with a precise description of its job. Identify what data comes in, what happens to it, and what result should come out. Then follow how variables hold and change values during those steps. These ideas let you check a plan before choosing a programming language, and help you spot instructions that leave the reader guessing.
1.1 Plan an algorithm with inputs, processes and outputs
An algorithm gives precise steps for completing a task. The steps have an order, a clear start, and an end. Each instruction must have one meaning, so another person can follow it without guessing.
Make the instructions precise
“Make the drink” leaves several choices unexplained. “Pour 200 ml of milk into the cup” names an action and an amount. “Repeat a few times” is vague; “Repeat 3 times” gives an exact count. A computer follows instructions literally. It cannot supply a missing calculation because the answer seems obvious.
An algorithm must give the right result for every input it is designed to handle. A plan that works for one test score but fails for another needs fixing.
Separate the plan from the program
A program expresses an algorithm in a programming language, such as Scratch or Python. A computer can run the program. A flowchart shows the plan using shapes and arrows. Pseudocode shows it using structured text. People read these plans to check the logic before writing code.
The two planning forms can describe the same steps. Flowcharts make branches easy to see. Pseudocode takes less space when there are many instructions.
Find the inputs and outputs
An input is data received by the algorithm. It might be a typed number or a sensor reading. A process works with that data through calculations, actions, or decisions. An output is a result, such as a message or a signal to a motor.
An IPO chart puts these parts in three columns. For the average of three test scores:
| Input | Process | Output |
|---|---|---|
| Scores 72, 85, and 90 | Add the scores, then divide by 3 | Average score |
The sum is 247. Dividing by 3 gives an average of 82.3 to one decimal place. The chart separates what comes in from what must be calculated. The average belongs under output, because it is the result we want.
A sensor can be an input even when nobody types anything. For a lamp controller, a light reading comes in, a decision checks it, and an output signal controls the lamp. The word “output” covers that signal as well as a message on a screen.
Choose the control structures
Three control structures organize the steps:
- Sequence runs steps one after another.
- Selection chooses a path using a decision.
- Iteration repeats a group of steps.
A ticket machine can read an age, choose a price, and repeat for another customer. That plan combines all three structures. Order matters within a sequence: calculate the price before displaying it. Displaying it first could show an old value or a value that has not been set.
Break up a larger problem
Decomposition means splitting a problem into smaller parts. A checkout needs to add item prices and work out change. Plan those parts separately, then connect them in the order needed. The total price must be ready before the change can be calculated.
Key Takeaways
- An algorithm has precise, ordered steps with a clear start and end.
- An IPO chart separates received data, processing, and results.
- Sequence, selection, and iteration organize algorithm steps.
- Flowcharts and pseudocode help people plan before coding.
1.2 Store and change values with variables
A variable stores a value under a name. The algorithm can read that value and replace it as the steps run. Names such as score, total, and count tell us what is being stored.
Read assignment from right to left
Assignment stores a value. In score ← 10, read the arrow as “score becomes 10.” The variable goes on the left. The value or calculation goes on the right.
For total ← total + 3, first read the current value of total. Add 3, then store the answer back in total. If it held 5, it now holds 8. The old 5 has been replaced.
This is an instruction, so it is fine to use the same variable on both sides. count ← count + 1 increases the stored count by 1; it is not an equation claiming that a number equals itself plus 1.
An assignment such as a ← b copies the current value of b. It changes a and leaves b unchanged. Choose names without spaces, such as highScore or high_score, so each name is easy to recognize.
For example, start with a ← 2 and b ← 6. After a ← b, both hold 6. If the next instruction sets b ← 9, a still holds 6. The assignment copied a value at one moment; it did not make the two names share every future change.
Keep assignment and comparison apart
| Instruction or condition | Meaning |
|---|---|
score ← 10 | Store 10 in score |
score == 10 | Ask whether score equals 10 |
score != 10 | Ask whether score differs from 10 |
A comparison gives true or false. It does not change the stored score.
Calculate with stored values
The arithmetic operators are + for addition, - for subtraction, * for multiplication, and / for division. Two more operators work with whole-number division:
17 DIV 5gives 3, the whole-number quotient.17 MOD 5gives 2, the remainder.
Five fits into 17 three times, leaving 2. A whole number is even when number MOD 2 == 0, because division by 2 leaves no remainder.
Read data and show results
INPUT name receives a value and stores it in name. OUTPUT shows a result. Quotation marks distinguish literal text from variable names. If name holds "Mia", then OUTPUT "Hello ", name shows "Hello Mia". But OUTPUT "name" shows the word "name".
Values also have types. An integer is a whole number; a decimal number can have a fractional part. A string is text. A Boolean is true or false. The number 7 can take part in arithmetic; the string "7" is text.
Follow a complete sequence
This algorithm finds a rectangle's area:
START
INPUT length
INPUT width
area ← length * width
OUTPUT area
END
With inputs 6 and 4, the calculation stores 24 in area. Only then does the output line show 24. An input must be stored before a later line uses it. The name area also makes the final output easier to understand than a name such as x.
Key Takeaways
- Assignment calculates the right side, then stores it on the left.
- A comparison tests values and returns true or false.
DIVgives a whole-number quotient;MODgives a remainder.- Quotation marks make an output literal text.
- Variables must receive values before those values are used.
2Draw and follow flowcharts
Flowcharts make an algorithm’s possible paths visible. Learn what each shape means, then follow its arrows through choices and repeated steps. A labeled decision shows which route a value takes; a returning arrow shows what repeats. Drawing these routes carefully helps you find missing actions and check exactly where an algorithm continues or stops.
2.1 Use the standard flowchart symbols
A flowchart shows an algorithm using shapes joined by arrows. Each shape tells you what kind of step happens there. Begin at Start and follow the arrowheads to read the algorithm.
Choose a shape for each step
| Symbol | Shape | What goes inside |
|---|---|---|
| Terminator | Oval or rounded rectangle | Start or Stop |
| Process | Rectangle | One action or calculation |
| Input/output | Parallelogram | An INPUT or OUTPUT instruction |
| Decision | Diamond | A true-or-false question |
| Predefined process | Rectangle with an extra vertical line inside each side | A named sub-routine |
| Connector | Small circle | A matching letter or number |
A terminator marks the start or finish. Use one Start in the main flowchart. More than one Stop is possible, although joining paths before one Stop often makes reading easier.
A process box can hold total ← total + price or an action such as "Switch on the light". Keep one action in each box. An input/output shape needs its instruction written inside: its shape alone cannot tell you whether data comes in or goes out.
Give decisions two labeled exits
A diamond holds a question such as temperature < 18?. Its two exits are labeled Yes and No, or True and False. Follow the exit that matches the current value. With a temperature of 16, follow Yes. With a temperature of 18, follow No.
Putting the question in a rectangle hides its role as a decision. Leaving the exits unlabeled makes the reader guess which action each answer chooses.
Draw a jacket algorithm
Draw a Start terminator, then an input parallelogram containing INPUT temperature. Connect it to a diamond asking temperature < 18?.
- The Yes arrow leads to
OUTPUT "Wear a jacket". - The No arrow leads to
OUTPUT "No jacket needed".
Both output steps use parallelograms. Join their arrows before the Stop terminator. The chart has six shapes: Start, input, decision, two outputs, and Stop. A person follows only one of the output paths on each run.
Connect longer plans clearly
A predefined process runs a named group of steps described elsewhere. A drawing robot might call drawSquare. The extra side lines distinguish this call from a single ordinary action.
Use connectors to continue a chart without a long or crossing line. A circle labeled A continues at the matching A circle. The label identifies one connection point; the arrowheads still show which way to travel.
Draw downward and left to right where possible. Put an arrowhead on every flow line. Every shape except Stop needs an outgoing line; Stop receives arrows and has none leaving it. Check each branch to its finish. A control system that keeps checking a sensor may deliberately loop continuously and have no Stop.
Key Takeaways
- Shape and label together tell you what a flowchart step does.
- A decision diamond has two labeled exits.
- Arrowheads give the order, including the route through connectors.
- A predefined-process box calls steps defined elsewhere.
2.2 Show decisions in flowcharts
Selection lets an algorithm choose a path. A decision diamond tests a condition, then its Yes and No arrows lead to different steps. The paths can join again before the algorithm continues.
Read the comparison exactly
A condition has a true-or-false answer. These operators compare values:
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
When age is 13, age >= 13 is true. But age > 13 and age != 13 are false. Equality matters at a boundary, the point where the chosen path changes.
Turn a rule into branches
“Children under 12 pay 5; everyone else pays 8” needs the condition age < 12. Draw Start, INPUT age, and that decision. The Yes path sets price ← 5; the No path sets price ← 8. Join the paths before OUTPUT price, then finish at Stop.
Age 9 follows Yes and outputs 5. Age 12 follows No and outputs 8. Using <= would include 12 in the lower-price group and change the rule.
Build more than two outcomes
One diamond has two exits. To award three medal bands, connect decisions in a chain. First ask score >= 80?. Yes outputs "Gold". No leads to score >= 50?. That diamond's Yes path outputs "Silver"; its No path outputs "Bronze".
A score of 79 fails the first test and passes the second. A score of 80 passes the first test immediately. It never reaches the second diamond.
The conditions overlap, so their order matters. Asking score >= 50? first and awarding Silver would catch 85 there too. The Gold branch would never receive that score. Check the highest band first in this chain, or give each range both limits.
Put one decision inside another
A nested decision appears on one branch of another decision. Suppose the first asks whether it is raining. Only its Yes path asks whether a parent is home. That second decision chooses between getting a ride and taking an umbrella. The first No path leads straight to walking. There is no need to ask the second question on that path.
You can trace a nested chart by writing down only the questions actually reached. With rain and no parent home, the route answers Yes, then No, and chooses the umbrella action. With no rain, it answers only the first question. Testing every diamond regardless of the arrows would add an action from a path that was never chosen.
Combine related conditions
AND is true when both parts are true. OR is true when at least one part is true, including when both are true. NOT reverses a condition's truth value.
The condition age >= 13 AND age <= 19 accepts ages 13 through 19. With OR, every age passes: an age below 13 meets the second part, and an age above 19 meets the first. Use parentheses when grouping conditions helps show the intended meaning.
After drawing decisions, follow every exit. Each must lead to an action, a joining point, another decision, or Stop.
Key Takeaways
- Check whether a boundary value belongs on the Yes or No path.
- A chain checks later decisions only along the arrows that reach them.
- Order overlapping conditions so the intended band is reached.
- An inner decision runs only on the outer branch that contains it.
ANDneeds both parts true;ORneeds at least one.- Every branch needs a route onward.
2.3 Show repetition in flowcharts
A backward arrow makes steps repeat. This is iteration, or a loop. A decision controls whether the flow goes around again or leaves the loop.
Repeat a fixed number of times
A count-controlled loop uses a counter. To output the numbers 1 through 5, connect these steps:
- A process sets
count ← 1. - A diamond asks
count <= 5?. - Its Yes exit leads to
OUTPUT count. - A process sets
count ← count + 1. - An arrow returns to the diamond.
- The diamond's No exit leads onward to Stop.
The initial assignment sits outside the returning path. The counter starts at 1 once, then changes to 2 after the first output. The final successful test uses 5. After outputting 5, the update makes the counter 6. The next test is false, so the algorithm stops.
If the arrow returned to count ← 1, the counter would restart on every pass. It would never reach the value needed to leave.
Repeat until an event happens
A condition-controlled loop does not need a known repeat count. Consider a password check. Input a password, then ask whether it equals "tiger7". The No exit outputs "Try again" and returns to the input. The Yes exit outputs "Welcome" and leaves.
Returning to the input matters. Returning only to the decision would test the same wrong password forever. New data must be read for the decision to change.
Place the test carefully
A test before the repeated actions can prevent them from running at all. A test after the actions allows at least one pass. In the password chart, the input happens before the first test, so a password is always entered at least once.
The arrows show whether a diamond controls selection or iteration. Two forward paths that join show selection. A path returning to an earlier step shows repetition.
Imagine changing the counting chart's starting value to 6. The first test count <= 5? is already false, so no number is output. If the output and update came before that first test, 6 would be displayed once. This is why moving a test across the body changes behavior, even when the same shapes appear in both charts.
Keep a running total
Set total ← 0 before a loop. Inside, read each number and use total ← total + number. For inputs 3, 5, 2, and 6, the total changes to 3, 8, 10, and 16.
Resetting total to 0 inside the returning path erases earlier additions. The final total would then be only the last number, 6. Initial values belong before the loop when they must be kept across passes.
Check that the loop can finish
A missing counter update leaves count at 1, so count <= 5 stays true. Changing the update to subtraction also fails: the counter moves farther below 5. Either mistake creates an infinite loop.
Loops intended to finish need a change that eventually reaches their exit. Some sensor-control loops run continuously on purpose. For a counting loop, also check the last pass: starting at 1 with < 5 outputs only 1 through 4. Using <= 5 includes 5 and prevents that off-by-one error.
Key Takeaways
- The backward arrow identifies the repeated steps.
- Initialize counters and totals before the returning path.
- A test before the body allows zero passes; a test after allows at least one.
- A loop intended to finish must eventually reach its exit.
- Trace the first and last pass to check the repeat count.
3Write algorithms in structured pseudocode
Structured pseudocode turns a plan into readable instructions. Write calculations in order, group choices with IF, and repeat steps with a suitable loop. Indentation shows which instructions belong together. You will also connect this text to flowcharts and use named procedures, so a longer plan stays clear while its decisions and repeats keep the intended behavior.
3.1 Write clear, structured pseudocode
Pseudocode describes an algorithm in short, structured lines. It looks like code, but it is written for people. You can check the logic without choosing a programming language.
Give each line one clear job
Use capital letters for keywords such as INPUT and OUTPUT. Put one instruction on each line. Begin a complete main algorithm with START and finish it with END. Use ← to store a value and comparison signs such as == or >= to test values.
“Get the numbers and work out the average” is not precise enough to trace. This version makes the inputs, calculation, and output visible:
START
INPUT a
INPUT b
INPUT c
average ← (a + b + c) / 3
OUTPUT average
END
The input lines store three values before the calculation uses them. The parentheses group the sum, so all three numbers are added before division.
With values 6, 9, and 12, the sum is 27 and the average is 9. Without parentheses, a + b + c / 3 divides only 12 by 3 before adding. It gives 19. Multiplication and division happen before addition and subtraction unless parentheses change that order.
Show blocks with indentation
An indented line starts farther to the right. Indent instructions inside a decision or loop. Their position shows which block they belong to:
START
INPUT temperature
IF temperature < 18 THEN
OUTPUT "Wear a jacket"
ENDIF
OUTPUT "Ready"
END
The jacket output runs only if the condition is true. The "Ready" output comes after the block and runs on either path. A line's position can change when it runs, so keep indentation consistent.
Match opening and closing keywords
| Opening | Closing |
|---|---|
IF ... THEN | ENDIF |
FOR ... TO ... | NEXT counter |
WHILE ... DO | ENDWHILE |
REPEAT | UNTIL condition |
PROCEDURE name | ENDPROCEDURE |
The closing keyword marks where a block ends. A missing ENDIF can make it unclear which later actions belong to the decision. Indentation and closing keywords work together; one does not replace the other.
Read other styles without mixing them
Pseudocode has no single worldwide spelling system. Other styles may use = or := for assignment, PRINT for output, or ENDFOR to close a FOR loop. Read their meanings, then use one consistent style when writing an algorithm. Follow a course's style when it sets one.
A programming language needs extra details. For example, Python can use age = int(input()) to read typed text and convert it into a whole number. The pseudocode line INPUT age leaves that language detail aside. The plan still needs precise steps: a line such as "sort out the answer" cannot be checked.
Key Takeaways
- Use one clear instruction per line.
- Indent the instructions inside each block.
- Match every block opening with its closing keyword.
- Parentheses show which calculation happens first.
3.2 Write decisions with IF statements
An IF statement chooses which instructions run. Its condition must be true or false. Indentation makes the chosen block visible, and ENDIF shows where the decision ends.
Choose one block
An IF without ELSE runs its block only when the condition is true. When false, it skips to the line after ENDIF. An IF with ELSE chooses exactly one of two blocks:
START
INPUT age
IF age < 12 THEN
price ← 5
ELSE
price ← 8
ENDIF
OUTPUT price
END
For age 12, age < 12 is false. The ELSE block sets price to 8. The output comes after ENDIF, so either branch reaches it. Using ← inside the condition would confuse storing a value with testing it.
Choose among several bands
An ELSE IF chain checks conditions from top to bottom. It runs the first true block and skips the remaining choices:
START
INPUT score
IF score >= 80 THEN
OUTPUT "Gold"
ELSE IF score >= 50 THEN
OUTPUT "Silver"
ELSE
OUTPUT "Bronze"
ENDIF
END
At 85, the first condition is true. The algorithm outputs "Gold" and leaves the chain. At 79, the first condition is false, so it checks the second and outputs "Silver". At 49, neither condition is true, so ELSE outputs "Bronze".
The highest band must come first in this chain. A first test of score >= 50 would catch 85 before it could reach Gold.
Distinguish a chain from separate tests
Separate IF statements each get their own test. If one tests score >= 80 and a later one tests score >= 50, a score of 85 passes both. It can produce two messages. Use a chain when the algorithm must choose one band; use separate tests when separate actions may both be needed.
Place one IF inside another
A nested IF sits inside a branch of an outer IF. Each needs its own ENDIF:
IF raining == TRUE THEN
IF parentsHome == TRUE THEN
OUTPUT "Get a ride"
ELSE
OUTPUT "Take an umbrella and walk"
ENDIF
ELSE
OUTPUT "Walk"
ENDIF
Only rain makes the inner test run. The inner ELSE deals with no parent being home. The outer ELSE deals with no rain. Indentation helps match each ELSE to its IF.
For a single action, nested tests can sometimes be joined. A club displays "Join" only when age is at least 13 and membership is current:
IF age >= 13 THEN
IF member == TRUE THEN
OUTPUT "Join"
ENDIF
ENDIF
The same action can use IF age >= 13 AND member == TRUE THEN. Both tests must pass in either plan. This replacement would need more care if the inner false branch also had an action.
Combine tests and compare text
age >= 13 AND age <= 19 requires both limits. OR requires at least one true part, so it cannot replace AND for this range. NOT (age < 13) reverses the test and means age >= 13.
Text comparisons also need care. answer == "yes" is false for "Yes" because the capital letter differs. Changing the input to lowercase before testing can make these entries match.
In a flowchart, THEN follows the diamond's Yes arrow. ELSE follows No. The paths join at the point represented by ENDIF.
Key Takeaways
- IF with ELSE runs exactly one of its two blocks.
- An ELSE IF chain runs only its first true block.
- Separate IF statements are tested independently.
- Each nested IF needs its own
ENDIF. - Text comparisons distinguish uppercase and lowercase letters.
3.3 Write loops with FOR, WHILE and REPEAT
Loops repeat a block of instructions. Choose the loop by asking whether the repeat count is already known, and whether the body must run at least once.
Count passes with FOR
A FOR loop manages a counter. With its default upward step of 1, both end values are included:
FOR i ← 1 TO 4
OUTPUT i * 7
NEXT i
The counter takes the values 1, 2, 3, and 4. The outputs are 7, 14, 21, and 28. At NEXT, the counter changes automatically. Do not add another counter increase inside the body.
Without STEP, the counter increases by 1. The pass count is last value minus first value plus 1 when the range counts upward by 1. Thus 1 to 5 gives five passes, but 0 to 5 gives six.
FOR i ← 2 TO 10 STEP 2 visits 2, 4, 6, 8, and 10. FOR i ← 5 TO 1 STEP -1 visits 5, 4, 3, 2, and 1. The step gives the direction and size of each change.
Test before repeating with WHILE
A WHILE loop tests before each pass. It repeats while the condition is true and stops when it is false:
number ← 1
WHILE number < 20 DO
number ← number * 3
ENDWHILE
OUTPUT number
The value changes from 1 to 3, then 9, then 27. The next test is false, so the output is 27. The test happens between passes; it does not interrupt multiplication when the value crosses 20. If the starting value already failed the test, the body would run zero times.
Test after repeating with REPEAT
A REPEAT ... UNTIL loop runs the body before testing. It stops when the UNTIL condition is true:
REPEAT
INPUT score
UNTIL score >= 0 AND score <= 100
The input instruction receives at least one score. A score outside the range leads to another input. A score of 0 or 100 ends the loop because both endpoints are allowed. WHILE repeats on true; UNTIL stops on true.
Use FOR for a known number of marks or laps. Use WHILE when a condition decides whether another pass is needed. Use REPEAT when an action, such as asking for input, must happen first. Python has no REPEAT keyword; a WHILE structure can perform that job.
Calculate an average after repetition
This complete plan reads four values. The total begins once, grows on each pass, and is divided only after all four inputs:
START
total ← 0
FOR i ← 1 TO 4
INPUT number
total ← total + number
NEXT i
average ← total / 4
OUTPUT average
END
For inputs 4, 6, 8, and 10, the stored totals are 4, 10, 18, and 28. Dividing 28 by 4 gives an average of 7. Putting OUTPUT average after the loop displays one final result; placing a total output inside would display intermediate sums instead.
Count inputs that meet a rule
A loop can also count inputs meeting a condition. Keep that count separate from the counter that tracks every pass:
passes ← 0
FOR i ← 1 TO 5
INPUT mark
IF mark >= 50 THEN
passes ← passes + 1
ENDIF
NEXT i
OUTPUT passes
Marks 72, 45, 50, 38, and 91 produce 3 passes. The mark 50 counts because >= includes equality. The loop counter tracks all five entries; passes tracks only entries meeting the rule.
A finishing WHILE loop must change data used by its condition. Missing the update in a counting loop leaves the test true forever.
Key Takeaways
- FOR includes both reachable endpoints and changes its own counter.
- WHILE tests before the body and can run zero times.
- REPEAT tests after the body and runs at least once.
- UNTIL stops when its condition becomes true.
- Initialize totals before the loop and update them inside.
- An IF inside a loop can count only values meeting a rule.
3.4 Convert between flowcharts and pseudocode and use sub-routines
A flowchart and pseudocode can express the same algorithm. Converting between them changes the form of the plan while keeping the same actions, decisions, and repeat paths.
Translate the meaning of each shape
| Flowchart step | Pseudocode |
|---|---|
| Start or Stop terminator | START or END |
| Input/output parallelogram | INPUT or OUTPUT |
| Process rectangle | Assignment or action |
| Decision with forward branches | IF ... THEN ... ELSE ... ENDIF |
| Decision with a returning path | A loop |
| Predefined-process box | CALL name |
Follow arrows from Start. At each diamond, inspect both routes. A returning route marks repetition. Two forward routes show selection. Indent the lines inside the corresponding block.
Keep the next input inside the loop
A password flowchart asks for input, tests it, and returns for another try after a wrong password. One translation is:
START
INPUT password
WHILE password != "tiger7" DO
OUTPUT "Try again"
INPUT password
ENDWHILE
OUTPUT "Welcome"
END
The first input supplies the value for the first test. The input inside the loop replaces a wrong attempt. Removing that second input would keep testing the same value.
Turn blocks back into arrows
Draw a shape for every action, input, output, and test. Closing words such as ENDIF, NEXT, and ENDWHILE tell you how to connect arrows. They do not need their own action boxes.
For an IF, label the diamond's Yes and No exits and join the paths where ENDIF occurs. For a WHILE, the test comes first and the body's last arrow returns to it. For REPEAT, the body comes first and the test's false route returns to the body.
Expand a FOR into initialization, test, body, update, and a returning arrow. For FOR i ← 5 TO 1 STEP -1, initialize 5, test i >= 1, run the body, then subtract 1. With the default upward step, add 1 and test i <= the final value.
Trace one boundary in both forms after converting. A countdown from 5 through 1 should output 1 before leaving. On the next return, its counter is 0 and i >= 1 is false. If the converted diamond tested i > 1, the text and drawing would differ: the drawing would miss the final 1.
Name a reusable group of steps
A sub-routine, also called a procedure, groups instructions under a name. Define it once, then use CALL wherever it should run:
PROCEDURE drawSquare
FOR side ← 1 TO 4
MOVE FORWARD 50
TURN RIGHT 90
NEXT side
ENDPROCEDURE
CALL drawSquare runs the four movement-and-turn pairs. When it finishes, execution returns to the line after the call. Calling it three times draws 12 sides. Defining it without calling it draws nothing.
In a flowchart, put drawSquare in a predefined-process box with extra vertical side lines. Show its detailed steps in a separate chart, beginning with a terminator containing the procedure name.
A named procedure keeps the main plan readable and allows repeated steps to be checked in one place. A supplied routine, such as one that plays a sound, can also be called by name.
For a main algorithm that should play a sound before drawing, put CALL playSound first and CALL drawSquare next. Each call completes before the following instruction begins. Their definitions can be kept separately, so the call order in the main plan stays easy to see.
Key Takeaways
- Follow the arrows to identify a branch or a loop before translating.
- Closing keywords control connections and do not need process boxes.
- A FOR flowchart must use the counter change and test matching its step.
- A procedure runs when called, then returns to the next instruction.
4Trace and test algorithms by hand
An algorithm can look sensible and still give the wrong result. Tracing follows its actual steps and records changing values. Testing compares those results with the problem’s rules. Use both to predict outputs, identify the algorithm’s purpose, and find the first faulty step. Carefully chosen boundary inputs often reveal errors that ordinary inputs miss.
4.1 Trace an algorithm with a trace table
Hand tracing means following an algorithm on paper, one instruction at a time. It is also called a dry run or desk check. A trace table records values so you can see what changes during the run.
Set up the table
Make a column for every variable and another for output. You can add condition columns to record true or false. Enter starting values, then follow the instructions in the order they actually run.
Add a row whenever a value changes or a new pass begins. Some tables leave unchanged cells blank; a blank then means no new value was written. A blank before any assignment means the variable has not received a value. Use one convention clearly so these meanings are not confused.
Only change the variable named on the left of the current assignment. Use values already stored, not values from lines that have yet to run. Record output only when an OUTPUT instruction is reached.
Trace a running total
START
total ← 0
FOR count ← 1 TO 4
total ← total + count
NEXT count
OUTPUT total
END
The table below leaves unchanged cells blank. Read their latest value above. The output column stays empty until the output line runs.
| Instruction reached | count | total | Output |
|---|---|---|---|
total ← 0 | — | 0 | |
| First counter value | 1 | ||
| Add count | 1 | ||
NEXT count | 2 | ||
| Add count | 3 | ||
NEXT count | 3 | ||
| Add count | 6 | ||
NEXT count | 4 | ||
| Add count | 10 | ||
| Final NEXT; leave loop | 5 | ||
OUTPUT total | 10 |
On the second pass, the stored total 1 is increased by the current count 2. That makes 3. On the third pass, 3 increases by 3 to make 6. Do not reset the total on each pass.
The final counter value 5 lies beyond the FOR range, so no fifth addition occurs. Its value can change without becoming an output. Keeping separate columns prevents the loop counter from being mistaken for the total the algorithm is asked to display.
Record tests and input changes
For number ← 1 followed by a WHILE loop multiplying by 3 while number < 20, test the current value each time. Values 1, 3, and 9 pass. Value 27 fails, so the body ran three times.
For a loop counting marks of at least 50, enter each mark when its input line runs. Marks 72, 45, 50, 38, and 91 give pass counts 1, 1, 2, 2, and 3. A false condition leaves the count unchanged.
See why assignment order matters
To swap a holding 3 with b holding 7, save one original value:
temp ← a
a ← b
b ← temp
After the first line, temp holds 3. The second stores 7 in a. The third stores the saved 3 in b. Without temp, a ← b followed by b ← a leaves both variables holding 7. The original 3 was overwritten.
A flowchart is traced the same way. Keep your place on the current shape, update the table at each process, and use current values to choose each decision's exit. In a FOR loop, the counter changes at NEXT, after the body, so keep that update in its proper place.
Key Takeaways
- A trace follows the actual path one instruction at a time.
- Use current values and change only what the current instruction changes.
- Record output only when the output instruction runs.
- A temporary variable can preserve a value before it is overwritten.
4.2 Predict, test and correct algorithms
A trace predicts what an algorithm does for one input. Testing compares that result with what the problem requires. A useful test can expose a wrong boundary, a missing branch, or a loop that ends too early.
Predict output and find purpose
Trace several different inputs to identify an algorithm's purpose. A decision that outputs a when a > b, and otherwise outputs b, gives 8 for inputs 3 and 8. It gives 9 for 9 and 2, and 5 for 5 and 5. Its purpose is to output the larger value, including the shared value when both are equal.
Describe that general job. “It outputs 8” describes only one run.
Work out the expected result first
The expected output comes from the problem's rules. The actual output comes from tracing or running the algorithm. Work out the expectation before checking the algorithm, so a faulty result does not become your answer key.
If expected and actual results differ, trace the steps to find the cause. Check the expected result too: a mistaken calculation in the test plan can make a correct algorithm appear wrong.
Choose tests that reveal different problems
| Data type | What it checks | Example for a score from 0 to 100 |
|---|---|---|
| Normal | A typical allowed value | 65 |
| Boundary | Values at or beside a limit | 0, 100, and values beside a band change |
| Invalid | A value to reject | -5, 105, or "ten" |
Boundary data is also called extreme data in some courses. Invalid data may be called erroneous data. For bands starting at 50 and 80, useful tests include 49, 50, 79, and 80. They check the exact points where messages change.
A test plan records the input, data type, expected output, actual output, and pass or fail. Number the tests so a failed case is easy to find. Record a pass only when actual and expected outputs agree.
Suppose a medal algorithm mistakenly uses score > 80 for Gold, with Silver beginning at 50. A short test plan exposes the wrong comparison:
| Test | Input | Type | Expected | Actual | Result |
|---|---|---|---|---|---|
| 1 | 85 | Normal | Gold | Gold | Pass |
| 2 | 80 | Boundary | Gold | Silver | Fail |
| 3 | 79 | Boundary | Silver | Silver | Pass |
The failure at 80 points to equality at the Gold threshold. Passing 85 alone would not find it.
Locate and repair a logic error
A logic error lets the steps run but produces the wrong behavior. This countdown should include 1:
count ← 5
WHILE count > 1 DO
OUTPUT count
count ← count - 1
ENDWHILE
It outputs 5, 4, 3, and 2. When count reaches 1, the condition is false before output can run. Change it to count >= 1 or count > 0. Retest the first and last passes to check the repair.
Debugging means finding and fixing errors. Other causes include a wrong initial value, steps in the wrong order, and a total reset inside a loop.
Check a changed rule
Suppose ticket prices gain a new band: people aged 65 and over pay 6. On the No exit of age < 12, add age >= 65. Its Yes path sets 6; No sets 8. Check 64 and 65, plus the child-price boundary, to make sure the new branch works with the old ones.
Test every decision exit and loops with zero, one, and many passes where possible. A few successful cases can still leave another path wrong. Fix the faulty rule, then repeat earlier tests to check the change.
Key Takeaways
- Expected results come from the problem; actual results come from the algorithm.
- Use normal, boundary, and invalid test data.
- Trace a failure to the first step that causes the wrong result.
- Retest earlier cases after a repair.
- Testing different paths reveals errors that one example can miss.
5Design and compare algorithms
A new problem may need several structures working together. Start with its data and rules, build a plan, and check it with test cases. Then compare possible solutions by the results they produce and the work they require. A useful choice also considers who must read the plan and which inputs it must handle, so speed is judged alongside correctness and clarity.
5.1 Design an algorithm for a new problem
Design starts with the job an algorithm must do. Write down the inputs, required outputs, and rules before choosing instructions. Then split the problem into parts you can plan and test.
Move from a problem to a plan
Use an IPO chart to identify data and results. Choose sequence for ordered actions, selection for choices, and iteration for repeated work. Write the plan as a flowchart or pseudocode, trace it, then improve the steps that fail a test.
A flowchart suits a short control plan with visible branches. Pseudocode is easier to change when there are many instructions. You can convert between them while keeping the same logic.
Design a change-giving algorithm
Suppose coins have values 100, 50, 20, 10, and 5 cents. The input is an amount to pay. The outputs are the coin values handed over. Use the largest available coin that still fits, subtract it, and try again before moving to the next smaller value.
For the 100-cent coin, one block is:
WHILE amount >= 100 DO
OUTPUT 100
amount ← amount - 100
coins ← coins + 1
ENDWHILE
Set coins ← 0 before any coin blocks. Repeat the same pattern for 50, 20, 10, and 5. Each block can give its coin several times; an IF would give it only once.
For 145 cents, give 100 and leave 45. Skip 50. Give 20 twice, leaving 5, then give 5. The result is four coins. For an amount of 0, every coin loop runs zero times, so no coins are given.
Handle amounts that cannot be paid
The amount must be a nonnegative whole number of cents. With 5 as the smallest coin, it must also be a multiple of 5. Otherwise a remainder would be left unpaid. The complete plan below accepts whole-number input and checks the other rules before giving coins:
START
INPUT amount
IF amount < 0 OR amount MOD 5 != 0 THEN
OUTPUT "Cannot pay this amount exactly"
ELSE
coins ← 0
WHILE amount >= 100 DO
OUTPUT 100
amount ← amount - 100
coins ← coins + 1
ENDWHILE
WHILE amount >= 50 DO
OUTPUT 50
amount ← amount - 50
coins ← coins + 1
ENDWHILE
WHILE amount >= 20 DO
OUTPUT 20
amount ← amount - 20
coins ← coins + 1
ENDWHILE
WHILE amount >= 10 DO
OUTPUT 10
amount ← amount - 10
coins ← coins + 1
ENDWHILE
WHILE amount >= 5 DO
OUTPUT 5
amount ← amount - 5
coins ← coins + 1
ENDWHILE
ENDIF
END
The ELSE is essential: an invalid amount must not continue into those blocks. An amount of 147 leaves 2 cents that these coins cannot pay.
Repeated coin blocks suggest a possible later improvement: one reusable routine for each chosen coin value. The simple repeated blocks still make the complete process easy to trace.
Combine decisions and repetition in a game
A guessing game needs input repeatedly, but its repeat count is unknown:
START
secret ← 42
REPEAT
INPUT guess
IF guess > secret THEN
OUTPUT "Too high"
ELSE IF guess < secret THEN
OUTPUT "Too low"
ENDIF
UNTIL guess == secret
OUTPUT "Correct"
END
Guesses 50, 30, and 42 produce "Too high", "Too low", and "Correct". The correct guess reaches neither message inside the IF. The UNTIL test then ends the loop, and the final output runs once.
Key Takeaways
- Identify inputs, outputs, and rules before writing the steps.
- Choose constructs to match choices and repetition in the problem.
- Keep invalid input away from the steps that require valid data.
- Trace zero values and boundaries as well as typical cases.
5.2 Compare algorithms that solve the same problem
Two algorithms can solve the same problem with different steps. Comparing them means checking what they get right, how much work they do, and how easy their plans are to understand.
Compare four features
| Feature | Question to ask |
|---|---|
| Correctness | Does it give the required result for every valid input? |
| Efficiency | How many operations or loop passes does it need? |
| Clarity | Is it easy to follow, check, and change? |
| Generality | Which range of inputs can it handle? |
Check correctness before choosing a fast method. A quick wrong answer does not solve the problem. The valid input range matters: a method that works only for positive values may fail when negatives are allowed.
Count the work as inputs grow
To add whole numbers from 1 through n, a loop starts at zero and adds each value. It performs n additions. A formula uses total ← n * (n + 1) / 2, requiring one addition, one multiplication, and one division.
For n equal to 100, both produce 5,050. The loop makes 100 additions, while the formula makes three arithmetic operations. At 1,000, both produce 500,500, but the loop now needs 1,000 additions. The formula still uses three operations.
These counts compare the stated arithmetic work. A loop also has counter and condition steps. Use the same counting rule for both algorithms. Timing one run on a computer mixes the algorithm with the machine's speed, and one small test says little about larger inputs.
Check the full input range
One even-number algorithm repeatedly subtracts 2 while the number is greater than 1. It then reports even only when the remaining value is 0. For 1,000, this needs 500 subtractions. Testing number MOD 2 == 0 needs one remainder operation.
The subtraction method also fails for -4. The loop never runs, and -4 is not 0, so it reports "odd". Yet -4 is even. This is both an efficiency problem and a generality problem when negative integers are valid inputs.
Challenge an apparently good method
Largest coin first gives the fewest coins for values 100, 50, 20, 10, and 5. Its success depends on the coin set. With coins of 1, 3, and 4, the same rule pays 6 as 4, 1, and 1. That is three coins. Two 3-cent coins pay the same amount with only two coins.
This single counterexample is enough to reject the claim that largest coin first always uses the fewest coins for every coin set. It still pays the full amount in this example; the failure concerns the requested minimum number of coins.
Balance speed and readability
A short written loop can execute thousands of times. A longer-looking plan can do less work. Written length is not an operation count.
Clarity matters when people must check or change an algorithm. Descriptive variable names and a short explanation can make a fast formula easier to follow. Choose among correct methods by the task: very large inputs may favor fewer operations, while a shared beginner project also needs readable steps.
Key Takeaways
- Compare correctness, efficiency, clarity, and generality.
- Count operations or passes with the same rule for both methods.
- Check how the work grows as the input grows.
- One counterexample can show that a general claim is false.
- Written length does not tell you how much work an algorithm executes.
Flowcharts and Pseudocode examples
1Turn a task into precise steps
12 steps
- 1IntroductionPlan before coding
Imagine a program that tells a robot what to do. The robot needs precise instructions, including where to begin and when to stop. Start by identifying the data and result, then put the actions in order.
We will plan an average-score algorithm and follow the values it stores. A flowchart or pseudocode can hold that plan before it becomes a program.
- 2ExplanationGive each step one meaning
An algorithm is a finite, ordered set of precise steps. “Repeat a few times” is unclear because readers may choose different counts. “Repeat 3 times” has one meaning.
A program writes the plan in a language a computer can run. Flowcharts and pseudocode describe the logic for people to inspect and share.
- 3ExampleSeparate data, work, and result
For an average of three scores, the inputs are 72, 85, and 90. Processing adds them to make 247, then divides by 3. The output is the average, 82.3 to one decimal place.
An IPO chart puts those three roles in separate columns. The average is the result we want; it is not another input to type.
- 4ConnectionChoose how steps are controlled
The average calculation uses sequence: read the scores, calculate, then output. A decision awarding a message uses selection. Asking for several scores in a loop uses iteration.
Order still matters inside a larger plan. An output placed before its calculation cannot show the newly calculated result.
- 5ChallengePlan a garden task
A program receives a garden's length and width and displays its perimeter. What belongs in the process part of its IPO chart?
---reveal---
Add the length and width, then multiply the sum by 2. The dimensions are inputs; the perimeter is output. The process describes how to obtain that result, not another measurement to enter.
- 6AnalogyGive a value a name
Think of a variable as a labeled place for a value. The label stays, but its contents can be replaced. A name such as
totalmakes the value's purpose clear.total ← 5stores 5 there. The arrow points toward the variable receiving the value. Nothing is displayed yet; output needs its own instruction. - 7ExampleReplace the old value
Now follow
total ← total + 3. The right side uses the stored 5 and calculates 8. Assignment then replaces 5 with 8 intotal.By contrast,
total == 8asks a true-or-false question and changes nothing. The assignment arrow stores a value; the equality comparison tests it. - 8TipRead names and literal text
Quotation marks make output literal text. If
nameholds "Mia",OUTPUT namedisplays "Mia".OUTPUT "name"displays the four letters "name".Numbers and strings also differ:
7is a number, while"7"is text. Integers, decimals, strings, and Booleans tell us what kind of value is stored. - 9ExampleUse quotient and remainder
DIVandMODdescribe different parts of whole-number division.17 DIV 5gives 3 because three full groups of 5 fit.17 MOD 5gives the leftover 2.For an even-number test, use
number MOD 2 == 0. An even integer divides into groups of 2 with no remainder. - 10ChallengeFollow a copied value
A plan starts with
a ← 4andb ← 9. It then runsa ← bfollowed byb ← b + 2. What values doaandbnow hold?---reveal---
aholds 9 andbholds 11. The first assignment copies the current 9 intoa. Changingbafterward does not change the value already copied intoa. - 11ChallengeConnect the plan to its output
A trip plan reads
distanceas 24 andspeedas 6. It calculatestime ← distance / speed, then runsOUTPUT "time". What does it display, and how can it display the calculated value?---reveal---
It displays "time". Remove the quotation marks:
OUTPUT timedisplays 4. The calculation stores a value; output decides what the user sees. - 12RecapCheck the data’s route
To inspect a short plan, locate its inputs and the result it should produce. Check that calculations happen after their inputs and before their outputs.
Read each assignment using current values. Then read each output literally: a variable name displays its contents, while quoted text displays exactly those characters.
2Follow choices and loops in a flowchart
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead the route through a chart
- 2ExplanationMatch a shape to its job
- 3ExplanationRead calls and connections
- 4ExampleDraw a jacket choice
- 5ChallengeRepair an unlabeled diamond
- 6ExampleCheck equality at the edge
- 7ExampleFollow a chain of bands
- 8Key InsightCombine the conditions of a range
- 9ChallengeChoose the first diamond
- 10ExampleBuild a returning path
- 11ExampleTrace the final pass
- 12TipLet the next pass change the data
- 13ExampleCarry a total through the loop
- 14ChallengeFix the wrong repeat count
- 15ChallengeKeep a repeated decision inside the loop
- 16RecapInspect every arrow
3Build readable decisions, loops, and calls
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the blocks visible
- 2ExampleWrite a precise sequence
- 3ChallengeFind the hidden order change
- 4TipShow where a block ends
- 5ExampleChoose one of two actions
- 6ExplanationLet the first true band win
- 7ExampleFollow a decision inside a decision
- 8ChallengeRepair a range test
- 9ExampleLet FOR manage its counter
- 10Key InsightUse a different step
- 11ExampleTrace a WHILE threshold
- 12ExplanationRead UNTIL as a stopping rule
- 13ExampleAdd only the values that qualify
- 14ChallengeCount after the change
- 15ConnectionTranslate block boundaries into arrows
- 16ExampleCall a named group of steps
- 17ChallengeConvert a countdown
- 18ChallengePut a call inside a repeated choice
- 19RecapRead the structure before tracing
4Trace a plan and find its first wrong step
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCompare the steps with the job
- 2ExplanationPrepare a trace table
- 3ExampleFollow the first two passes
- 4ExampleFinish the trace before output
- 5TipPreserve a value before replacing it
- 6ChallengeTrace only the chosen branch
- 7ExplanationDescribe purpose beyond one run
- 8ExampleChoose revealing test inputs
- 9ExampleFind the missing final output
- 10ChallengeChoose a test for a changed boundary
- 11ChallengeDiagnose a total that restarts
- 12RecapUse a failure to improve the plan
5Design a solution and compare its work
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDefine what success means
- 2ExplanationSplit the coin task
- 3ExampleTrace the payment
- 4TipKeep invalid amounts out
- 5ChallengeDesign one repeated coin block
- 6ConnectionChoose a loop for unknown attempts
- 7ExplanationCompare the right features
- 8ExampleCount work for a larger input
- 9ExampleFind an input the method misses
- 10ChallengeTest the minimum-coin claim
- 11ChallengeChoose between two correct plans
- 12RecapJudge against the actual task
Flowcharts and Pseudocode practice questions
Set 1: Connect branches, loops, and tests10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
age >= 11 AND age <= 15?. For ages 10, 11, and 16 in that order, what exits are followed?Show answerHide answer
Question 4 of 10
How many times does OUTPUT n run?
n ← 18
WHILE n < 18 DO
OUTPUT n
n ← n + 1
ENDWHILE
Show answerHide answer
18 < 18, which is false. WHILE checks before entering its body, so the output and update are both skipped. One output would fit a body that runs before its test, as in REPEAT, but not this WHILE structure.Question 5 of 10
What is output for inputs 4, 7, 2, and 9?
total ← 0
FOR i ← 1 TO 4
INPUT n
IF n MOD 2 != 0 THEN
total ← total + n
ENDIF
NEXT i
OUTPUT total
Show answerHide answer
Question 6 of 10
CALL chime, then OUTPUT "Done". The procedure outputs "Ring" twice and finishes. What is the output order?Show answerHide answer
Question 7 of 10
What pair is output?
a ← 6
b ← 11
temp ← a
a ← b - 2
b ← temp + a
OUTPUT a, b
Show answerHide answer
temp preserves 6, and a ← b - 2 stores 9 in a. The last assignment uses the saved 6 and current 9 to store 15 in b. Getting 20 would use the old 11 instead of the new value of a in that final calculation.Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
n for positive integers. A adds every value in a loop; B uses n * (n + 1) / 2. Counting arithmetic only, what are their counts at n = 250 and n = 500?Show answerHide answer
Set 2: Read the steps and follow the values10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
points hold after points ← 13 followed by points ← points - 4?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
OUTPUT "Door open"?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
tickets < 6?. Yes sets fee ← 2; No sets fee ← 0. Both paths lead to OUTPUT fee. What is displayed when tickets is 6?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
count ← 3, then tests count <= 7?. Yes outputs count, adds 1, and returns to the test. No stops. How many values are output?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
WHILE ... DO?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What message is output when badges is 7?
IF badges >= 10 THEN
OUTPUT "Leader"
ELSE IF badges >= 5 THEN
OUTPUT "Helper"
ELSE
OUTPUT "Member"
ENDIF
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What values does this loop output?
FOR i ← 3 TO 9 STEP 3
OUTPUT i
NEXT i
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What is the final output?
x ← 2
FOR i ← 1 TO 3
x ← x + i
IF x >= 5 THEN
x ← x - 1
ENDIF
NEXT i
OUTPUT x
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace changes and diagnose failures10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
CALL playTune, where playTune is defined elsewhere?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
count ← 2 and total ← 0. It tests count <= 6?; Yes adds count to total, increases count by 2, and returns. No outputs total. What is output, and why does the next test leave?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
OUTPUT "Low" inside IF level < 3 THEN ... ENDIF, then runs OUTPUT "Checked" after ENDIF. What is output for level 5?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What messages are output for score = 86?
IF score >= 75 THEN
OUTPUT "Top"
ENDIF
IF score >= 40 THEN
OUTPUT "Ready"
ELSE
OUTPUT "Retry"
ENDIF
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What is output for successive inputs 5, 12, and 8?
total ← 0
REPEAT
INPUT n
total ← total + n
UNTIL n >= 10
OUTPUT total
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
entry, tests entry == 0?, and stops on Yes. No outputs "Again" and returns to read a new entry. After the initial input, what WHILE condition matches that route?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is the final output for inputs 3, 8, and 5?
best ← 0
FOR i ← 1 TO 3
INPUT n
IF n > best THEN
best ← n
ENDIF
NEXT i
OUTPUT best
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
total ← 0, then adds the number. Moving the initialization repairs it. What expected outputs test both the old failure and the all-zero case?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
remainingSeats; the other uses unexplained single letters. What feature is most directly improved by descriptive names?Show answerHide answer
Save this lesson to see this answer.
Set 4: Apply the rules to new plans10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
29 MOD 6?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is output?
a ← 5
b ← 8
a ← a + b
b ← a - b
a ← a - b
OUTPUT a, b
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
points = 11 and bonus = true. Its first diamond tests bonus == TRUE?; Yes adds 5 to points, and No leaves it unchanged. The paths join at points >= 10?, which sets level to 2 on Yes and 1 on No. A final diamond tests points >= 14?; Yes adds 1 to level, while No leaves it unchanged. What does OUTPUT level display?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
count ← 1 and total ← 0. While count <= 5, it adds count to total and increases count by 2. It should add every integer from 1 through 5. What does it currently total, and what update repairs it?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
a = 10 and b = 4, what does result ← a + b * 2 store?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What messages are output for age = 10 and member = true?
IF age < 14 THEN
IF member == TRUE THEN
OUTPUT "Junior member"
ELSE
OUTPUT "Junior guest"
ENDIF
ENDIF
IF member == TRUE THEN
OUTPUT "Member desk"
ENDIF
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
INPUT code, then loops back to that input while code is not "go". A translation has one INPUT before WHILE but none inside. What instruction is missing from the repeated body?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
boxes >= 2 OR boxes <= 8. Tests with 2, 5, and 8 all pass. What pair of tests reveals the defect on both sides, and what complete condition repairs it?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Actual output
Algorithm
Arithmetic operator
area ← length * width uses the multiplication operator to calculate the stored area.Assignment
total ← total + 4, the old total is read before the increased value replaces it.B
Block
Boolean
score >= 50 produces true for 50 and false for 49 without changing the score.Boundary data
C
Call
CALL playTune, the main algorithm waits for the tune routine to finish before its next output.Case-sensitive comparison
"go" fails for "Go" unless the input is changed to matching case before testing.Clarity
total and count clearer than unexplained single letters.Comparison operator
age >= 16 includes age 16, while the sign in age > 16 excludes that boundary.Condition
count <= 4 stays true at 4, allowing that final pass before the counter increases.Condition-controlled loop
Connector
Conversion
Correctness
Count-controlled loop
Counterexample
D
Debugging
Decision symbol
age < 12?, age 12 follows No because the less-than sign does not include equality.Decomposition
DIV
23 DIV 5 gives 4, counting the complete groups; the leftover 3 is found using MOD.E
Efficiency
ELSE branch
age < 12 is false, ELSE assigns the standard price before both routes reach the output.ELSE IF chain
Expected output
F
Flow line
Flowchart
FOR loop
FOR i ← 2 TO 5 runs four times by default and changes the counter automatically at NEXT.G
Generality
H
Hand tracing
I
IF statement
Indentation
Infinite loop
count <= 5, so that counting loop cannot finish.Input
Input validation
Input/output symbol
INPUT age or OUTPUT price; the words distinguish their jobs.Integer
Invalid data
IPO chart
Iteration
K
Keyword
ELSE introduces the block followed when the preceding IF condition is false.L
Logic error
count > 1 has a logic error if its required final output is 1.Logical operator
Loop counter
i can track five inputs while a separate variable counts only inputs that meet a condition.M
MOD
23 MOD 5 gives 3 because four complete groups of 5 leave 3 out of the original 23.N
Nested decision
Normal data
O
Off-by-one error
count < 5 gives four passes when the intended range is 1 through 5.Output
P
Predefined-process symbol
drawSquare runs the square-drawing steps before the main chart continues.Procedure
drawSquare procedure for a robot keeps four movements and turns together for repeated calls.Procedure definition
PROCEDURE beep with its body defines the routine, but no beep occurs until it is called.Process symbol
count ← count + 1 changes the counter before the next decision test.Processing
Program
Pseudocode
INPUT age before its language-specific input and conversion code is written.R
REPEAT ... UNTIL loop
Running total
S
Selection
Sequence
Step
STEP -1, a loop counts down from 6 through 2 instead of increasing its counter.String
"17" is a string of two digits, while 17 is a number that can take part in arithmetic.T
Temporary variable
a in temp lets a swap recover it after a has received the value of b.Terminator
Test case
Test plan
Trace table
V
Variable
remainingSeats decreases when the booking algorithm accepts another reservation.W
WHILE loop
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.