- Learn
- Computer Science & IT
- Computer Science
- Introduction to Computer Science
- Computational Thinking and Problem Solving
Computational Thinking and Problem Solving
BeginnerLesson 1 of 7 in Introduction to Computer Science Course
What you will learn
- Describe what computer science studies, how it differs from programming alone, and how computational thinking turns a problem into a solution that a person or a computer can carry out.
- Describe what computer science studiesExplain computer science as the study of computation and information, name its main areas, and describe every computation as turning input into output.
- Describe computational thinking and its four techniquesDefine computational thinking, name decomposition, pattern recognition, abstraction and algorithm design, and use them together in a problem-solving process.
- Describe what computer science studies
- Use decomposition, pattern recognition and abstraction to turn a large, unclear problem into small, general parts that are easy to solve.
- Decompose a problem into manageable partsBreak a problem into subproblems, organize them in a hierarchy, and decide when a part is small enough to solve directly.
- Recognize patterns and generalize solutionsFind similarities within and between problems, reuse solutions for repeated parts, and generalize a pattern so that one solution covers many cases.
- Use abstraction to focus on what mattersKeep the details a purpose needs, hide the rest, and use models and named procedures as abstractions with clear inputs and outputs.
- Decompose a problem into manageable parts
- Describe what makes an algorithm correct and useful, and write algorithms in pseudocode with variables, input and output, decisions and loops.
- Explain what an algorithm is and what makes one goodDefine an algorithm, test instructions for precision and completeness, and compare different algorithms for the same problem by correctness and number of steps.
- Store and change data with variables, input and outputWrite pseudocode that reads input, stores and updates values in variables, calculates with operators and produces output.
- Make decisions with selectionWrite conditions with comparison and logical operators, and use IF, ELSE and ELSE IF so that an algorithm takes the right path for every input.
- Repeat steps with loopsUse count-controlled and condition-controlled loops, keep running totals and counts, and avoid infinite loops and off-by-one errors.
- Explain what an algorithm is and what makes one good
- Draw and read flowcharts, convert between flowcharts and pseudocode, and check algorithms by tracing them and testing them with well-chosen data.
- Read and draw flowchartsUse the standard flowchart symbols and flow lines to show the steps of an algorithm and read the path it takes.
- Show decisions and loops in flowcharts and pseudocodeDraw selection and iteration in flowcharts and translate an algorithm in either direction between flowchart and pseudocode.
- Trace, test and debug an algorithmCheck an algorithm by hand with a trace table, choose normal, boundary and invalid test data, and find and fix the three kinds of errors.
- Read and draw flowcharts
- Use a block-based environment such as Scratch to build programs with sequence, loops, decisions, variables, events and custom blocks, and connect them to pseudocode and text-based code.
- Find your way around a block-based environmentExplain how block-based programming works, name the parts of a Scratch project, and use block shapes and categories to build a script.
- Build programs with loops, decisions and variables in blocksUse repeat, forever, if-else and repeat-until blocks, variables and the ask block to build interactive programs, and read them as algorithms.
- Use events, custom blocks and the move to text-based codeStart scripts with events, coordinate sprites with messages, define custom blocks with inputs, and carry the same ideas over to text-based languages.
- Find your way around a block-based environment
Computational Thinking and Problem Solving study guide
1What computer science asks and how to approach a problem
Computer science begins with questions about information and the processes used to handle it. Describing a task through its inputs and outputs makes the goal clear before any code is written. Computational thinking then supplies ways to organize the work, spot reusable structure, select the details that matter, and build a solution that can be checked. Those methods are useful in everyday planning as well as in programs.
1.1 Computation, information, and the problems they solve
A computer can calculate a route, play a sound, or organize a list of names. Computer science studies the processes behind these tasks: how information is represented and handled, which problems can be solved, and how to build systems that carry out the solutions.
Describe a computation
A useful starting model is input → process → output. A route planner receives a start point and a destination. It searches information about roads, then returns a route, a distance in kilometers, and a travel time. The road information is also data the process needs. The visible result is only one part of the computation.
State a computational problem before choosing its method. For example: “Input: a list of names. Output: the same names in alphabetical order.” This specifies what a correct result must look like. It leaves room for different methods of producing it. If the output drops a name, it fails the problem even when the remaining names are ordered.
More than writing code
Programming is writing instructions in a language a computer can run. It is an important activity within computer science. The wider field also asks whether a solution exists, how much work it needs, and how people can use it safely and easily.
| Area | A question it studies |
|---|---|
| Algorithms and theory | What steps solve a problem, and what can be computed? |
| Programming languages | How can instructions be expressed clearly? |
| Computer systems | How do hardware, operating systems, and networks support computation? |
| Data and databases | How can information be stored, organized, and retrieved? |
| Artificial intelligence and machine learning | How can systems perform tasks such as recognizing patterns? |
| Human–computer interaction | How can people understand and use a system? |
| Security | How can data and systems be protected? |
| Computer graphics | How can images be created and displayed? |
| Software engineering | How can teams build and maintain reliable programs? |
The boundaries overlap. Designing an image editor can involve graphics, user interaction, and software engineering at once. Computing also supports other disciplines: biologists compare DNA sequences, climate scientists model the atmosphere, and artists use software to create images and music.
Related fields and practical limits
Computer engineering focuses on physical devices such as processors and circuit boards. Information technology, or IT, focuses on choosing, setting up, and running systems for an organization. Data science combines statistics and computing to draw conclusions from data. These fields share methods with computer science while emphasizing different work.
Computers execute precise instructions quickly, often billions of simple operations per second. Speed does not repair an unclear instruction. “Add some salt” leaves a quantity unstated; a process intended for automatic execution needs a precise action.
There are also limits beyond speed. Some precisely stated problems have no algorithmic solution. Other problems have solutions that require too many steps to be practical. Asking what a computer can accomplish is part of computer science itself.
Key Takeaways
- Computer science studies computation, information, and the systems that process it.
- A problem statement defines valid inputs and required outputs before a method is chosen.
- Programming expresses instructions; computer science also studies correctness, usability, security, and computational limits.
- Input, process, and output describe the roles of data and steps in a computation.
1.2 Turn a problem into a plan you can check
Computational thinking makes a problem clear enough to solve step by step. A person may carry out the solution, a computer may carry it out, or the two may share the work. The thinking includes deciding what the problem means and how a result should be checked.
Four techniques that work together
Decomposition breaks a problem into smaller parts. Pattern recognition finds similarities or repeated work. Abstraction keeps the details needed for a purpose and leaves out others. Algorithm design turns a solution into precise, ordered steps.
These techniques are tools you can return to as needed. They are not four boxes that must be completed in a fixed order. A failed test might reveal a missing subproblem. A repeated subproblem might suggest a reusable procedure. A model might need one more detail before the algorithm can work.
Jeannette Wing helped make the term “computational thinking” widely known in a 2006 essay. Her central message was that this approach is useful to everyone, beyond people employed as programmers.
Understand, plan, carry out, and check
The mathematician George Pólya described four problem-solving stages in 1945. In computing, they lead to concrete actions:
- Understand the problem. Identify inputs, outputs, constraints, and success criteria.
- Make a plan. Choose smaller tasks, useful patterns, and an algorithm.
- Carry out the plan. Express and execute it with pseudocode, a flowchart, or a program.
- Look back. Compare the result with the success criteria and revise the solution where needed.
A constraint is a rule the solution must respect, such as a maximum available time. A success criterion is a way to judge the result. “Produce a combined shopping list with the required quantities” is checkable. “Make shopping better” leaves the result unclear.
Work through a meal plan
Suppose you need evening meals for a week. The inputs include the recipes, the number of people, and food already available. The output is a plan and a shopping list. Dietary needs and available cooking time are constraints.
Decompose the work into choosing meals, making the list, and cooking. Pattern recognition shows that several recipes use rice and onions. Abstraction represents an ingredient by its name and quantity, such as “rice, 1 kg,” without keeping a brand name when the brand does not affect the plan.
The shopping algorithm can now be ordered: choose the meals, list their ingredients, combine repeated ingredients, subtract what is already in the cupboard, and shop for what remains. Combining quantities before checking the cupboard prevents the same stock from being subtracted separately for every recipe.
Check the result against the meals. Every needed ingredient must be available in sufficient quantity. If an ingredient is missing, trace how the list was built and revise the relevant step.
A common failure is to start coding before deciding what result is needed. A fast program can faithfully solve the wrong problem. People still choose the model, constraints, and steps; the computer executes the instructions that express those choices.
Key Takeaways
- Computational thinking makes solutions precise enough for people or computers to carry out.
- Decomposition, pattern recognition, abstraction, and algorithm design can be used in any useful order.
- Write inputs, outputs, constraints, and success criteria before implementing a solution.
- Use tests to guide revisions to the plan, model, or steps.
- The approach applies to everyday planning as well as software.
2Break problems into useful, reusable parts
A complicated task becomes easier to solve when its parts, repeated structures, and essential details are visible. Decomposition gives each part a job, pattern recognition reveals methods you can reuse, and abstraction lets you work with a simpler model. The examples here show how to choose those boundaries and check that the simplified plan still contains everything needed to finish the original task.
2.1 Split the work into parts that fit together
A large problem can be hard to hold in mind all at once. Decomposition replaces it with smaller subproblems that you can understand, solve, and check separately. The parts must still combine into a solution to the original problem.
Work from the whole to the details
Start with the main job. Divide it into a few meaningful responsibilities, then refine each responsibility. This is top-down decomposition. A tree-shaped decomposition diagram places the whole problem at the top and the smaller tasks beneath it. The branches show which task a smaller task belongs to.
For a quiz app, the main parts are storing questions and answers, asking questions, checking answers, and keeping and showing the score. The “ask a question” part can be split into showing the question text, showing the answer options, and reading the learner's choice.
A textual structure chart could look like this:
Run a quiz
Store questions and answers
Ask a question
Show question text
Show answer options
Read the choice
Check the answer
Keep and show the score
These branches describe responsibilities. Their vertical position alone does not give the full execution order. For example, the app repeats asking and checking while questions remain. A separate algorithm describes that flow.
Decide when to stop splitting
A part is small enough when you can see how to solve it directly, or when an existing method or tool handles it. “Read the choice” may be a usable task once you know how the interface collects input. Splitting it into individual hand movements would add detail that does not help design the app.
Do the main split first. If you begin by describing tiny actions, it is easy to spend time on one screen while forgetting an entire responsibility, such as deciding when the quiz ends.
Identify dependencies
A dependency means one task needs another task's result. The quiz must obtain a choice before checking it, and check it before updating the score. Write down what each part receives and produces. This makes the handoffs clear.
Parts should be as independent as possible. If the display changes from four answer buttons to another input method, the score calculation should still work with the checked result. Clear boundaries let people build separate parts at the same time and make later changes easier.
Independence does not mean the parts never exchange information. They need agreed inputs and outputs. A scoring part that expects TRUE or FALSE cannot directly use a question-display part's raw text without a step that checks the answer.
Look for gaps and overlap
Read the original problem again and ask whether completing every part would finish the whole job. The first chart does not show when the quiz stops. Add that responsibility to the overall quiz control. Also ask whether two parts both change the score, which could count a correct answer twice.
Check each small part on its own, then check the combined process. A correct question display and a correct answer checker can still fail together if one sends a different choice format from the one the other expects.
Key Takeaways
- Decomposition separates a whole problem into smaller responsibilities.
- Refine the main parts before describing their tiny actions.
- Stop when a part can be solved directly or handled by an existing solution.
- Dependencies determine which results must be available before another task starts.
- Check that the combined parts leave no gaps and perform no job twice.
- Clear inputs and outputs make separate parts easier to build and combine.
2.2 Find the pattern and make it reusable
Repeated work often hides a reusable method. Pattern recognition means looking for similarities, repetitions, or trends within a problem and across different problems. The useful question is what stays the same and what changes.
Find repetition inside a task
To draw a square, a moving pen can move forward 100 steps and turn right 90 degrees, four times. The pair of actions repeats. A loop expresses that pair once and supplies the repetition count:
REPEAT 4 TIMES
Move forward 100 steps
Turn right 90 degrees
This pattern makes the structure easier to see. It also makes a change easier: changing the forward distance in one place changes every side.
Replace changing details with parameters
Generalization makes one solution work for a family of cases. A parameter is a named input representing a detail that can change. For regular polygons, the side count and side length can be parameters.
A pen walking around a regular polygon turns through one complete revolution. The turn at each corner is:
Here, is the number of sides. Repeat the move-and-turn pair times, keeping the same side length and turn each time.
| Regular polygon | Sides | Turn at each corner |
|---|---|---|
| Triangle | 3 | 120° |
| Square | 4 | 90° |
| Pentagon | 5 | 72° |
| Hexagon | 6 | 60° |
The turn is the change in the pen's direction, not the interior angle of the polygon. For a triangle, using a 60-degree turn would not produce the intended three-sided path.
Recognize the same method in different problems
Finding the cheapest flight, shortest route, and highest test score all involve remembering the best candidate seen so far. Begin with a candidate. Inspect each next candidate and replace the remembered one when the new one is better. The direction of the comparison changes between lowest and highest, but the overall pattern remains useful.
Patterns can also organize data. Grouping expenses into food, transport, and housing makes shared features visible. If umbrella sales repeatedly rise when rain is forecast, a shop can use the trend to help plan stock. A trend is evidence to examine; the reason it holds matters when deciding whether it will continue.
Check the proposed pattern
The numbers 1, 2, 4 do not uniquely determine the next number. Doubling gives 8. Increasing the gaps by one gives 7, since the gaps so far are 1 and 2. More cases or a rule explaining the sequence are needed to decide which pattern fits the problem.
Look for meaningful differences before reusing a solution. Splitting a bill equally and splitting it according to what each person ordered both involve a shared total. Equal division solves the first task, but the second needs each person's order. Reuse the common structure only after identifying the detail that changes the required result.
Key Takeaways
- Pattern recognition finds reusable structure within and between problems.
- Generalization replaces changing details with named parameters.
- A regular polygon with n sides uses n equal moves and turns of 360° / n.
- Check more cases and meaningful differences before trusting a pattern.
2.3 Keep the details the purpose needs
A model can be simpler than the real thing and still be useful. Abstraction keeps the information needed for a particular purpose and leaves out other details. Its quality depends on whether it can answer the questions the task asks.
Choose a model for the job
A metro map keeps stations, their order along each line, and places where lines connect. Those details help a traveler plan a journey. It can distort distances and omit street layouts because its main purpose is to show connections.
That same map is a poor tool for deciding how far to walk between two stations. The model left out a detail that the new purpose needs. A detail is relevant because of the problem, not because it is interesting in general.
Consider two models of the same car:
| Purpose | Details the model needs |
|---|---|
| Racing game | Speed, position, and direction |
| Parking-garage system | License plate number, arrival time, and parking space |
The racing game needs to update movement. The garage needs to identify the car and track its visit. Neither model must preserve every physical feature of the car.
Hide steps behind a clear name
Abstraction also lets you use what a component does without thinking through how it works each time. Selecting a washing-machine program does not require you to control its motor directly.
In an algorithm, a procedure is a named group of steps. Calling the name runs those steps. A name such as average(list) communicates a job while hiding the repeated arithmetic. A procedure that sends a result back to its caller returns a value. The caller can store that value or use it in another calculation.
A parameter gives a procedure an input that can change. drawPolygon(sides, length) has two parameters. The call drawPolygon(6, 100) supplies six sides and a length of 100 steps. This combines abstraction, which hides the drawing steps, with generalization, which supports different shapes and sizes.
A procedure's boundary needs to be clear: what inputs does it accept, and what result or action does it produce? For an average, an empty list needs special handling because there is no count to divide by. Hiding steps does not remove the need to define usable inputs.
Build layers of understanding
A chat app offers a way to send a message. Beneath it, the operating system offers services the app can use. Beneath that, hardware carries out operations. Each layer relies on the next layer's behavior without exposing every internal detail to its user. An internal change can be contained when the promised behavior stays the same.
The techniques support one another. Decomposition identifies parts. Pattern recognition finds parts with a shared structure. Abstraction gives those parts names and clear boundaries so they can be combined.
A common abstraction error is deleting a fact that changes whether a result works. A route planner that ignores one-way streets can propose an impossible drive. To check a model, list the decisions it must support and confirm that the kept data is enough for each one.
Key Takeaways
- Abstraction keeps information relevant to a purpose and hides unnecessary detail.
- The same object can need different models for different tasks.
- A procedure names reusable steps; parameters supply inputs, and a returned value goes back to the caller.
- A procedure with parameters can provide both abstraction and generalization.
- Layers let one component rely on another component’s behavior without exposing all its internal steps.
3Express algorithms with variables, decisions, and loops
An algorithm turns a plan into instructions whose behavior can be followed exactly. Variables hold the changing state, conditions choose paths, and loops repeat work until a count or condition ends it. Working through these structures line by line shows why instruction order matters. You will also compare methods by correctness and step counts, then use pseudocode to express calculations, choices, and repeated processing.
3.1 Write a method that finishes and gives the right result
An algorithm is a finite, ordered set of precise instructions for solving a problem or completing a task. For valid input, it produces the required output after a finite number of steps. A recipe, assembly instructions, and long division all use this idea.
Check the method's properties
A useful algorithm has defined inputs and outputs. Each step must be precise enough to have one meaning and effective enough to carry out. The steps must finish, and their result must be correct for every valid input.
“Find the largest number” names a goal, but it does not specify a method. “Inspect each number and keep the largest seen so far” gives a method that can be developed into instructions. It also raises an input question: what should happen if the list is empty? Defining valid input avoids leaving the method unfinished.
Everyday instructions can leave gaps that people fill from experience. “Put the jam on the bread” leaves out opening the jar and spreading a quantity on a surface. When designing a method for automatic execution, state the actions the executing system needs and put them in a usable order.
Separate the method from its expression
An algorithm is the solution method. A program expresses a method in a programming language so that a computer can execute it. The same algorithm can appear in pseudocode, in a flowchart, and in programs written in different languages.
Three control structures organize the execution:
| Structure | What happens |
|---|---|
| Sequence | Steps run one after another. |
| Selection | A condition chooses a path. |
| Iteration | A block of steps repeats. |
Together with variables, these structures are sufficient to express any algorithm. This is the idea behind a classic result published by Böhm and Jacopini in 1966. An algorithm can combine them: repeat over a list, test each value, and update a stored result in sequence.
Compare correct methods
Suppose an alphabetically ordered phone book has 1,000 pages. Checking pages one at a time can require 1,000 page checks. Turning two pages at a time and checking only every other page takes up to about 500 checks, plus one step back if the name was passed.
A different method opens the remaining section in the middle and keeps the half that can contain the name. At most 10 halvings reduce 1,000 possible pages to one:
1000 → 500 → 250 → 125 → 63 → 32
→ 16 → 8 → 4 → 2 → 1
The sorted order makes discarding a half safe. Without that order, the discarded half could contain the name. This input assumption belongs to the method.
For 2,000 pages, checking every page can take twice as many checks, while halving takes only one more halving: 11. Comparing how step counts grow explains more than timing one run on one machine.
Check correctness before praising speed. A method that examines only the first and last number in a list happens to find 12 in [7, 3, 12]. It misses 12 in [7, 12, 3]. One successful example cannot establish that the method handles the full input range.
Key Takeaways
- An algorithm must be precise, effective, finite, and correct, with defined inputs and outputs.
- An algorithm is a method; a program expresses instructions in an executable language.
- Sequence, selection, and iteration organize algorithm steps.
- An algorithm’s input assumptions must hold for its reasoning to be valid.
- Compare correct methods by how their work grows as the input grows.
3.2 Store values and update them in order
Pseudocode describes an algorithm with structured, readable instructions. It is not tied to one programming language. It lets you work on the logic before handling a language's punctuation and other writing rules.
Read the notation
Keywords are capitalized: INPUT, OUTPUT, IF, WHILE, and FOR. Each instruction has its own line. Indentation shows which instructions belong to a block. A comment begins with // and explains the code without adding an action.
The arrow ← means assignment. Some other pseudocode styles use = or SET … TO for assignment. Here, = compares values. Read count ← 0 as “count gets zero.” A variable is a named place storing a value that can change. A constant has a name but keeps the same value, such as PASS_MARK ← 50.
The right side of an assignment is evaluated first. Its result replaces the old value on the left. If count holds 4, count ← count + 1 reads the old 4, adds 1, and stores 5. It is an instruction to change stored data, not an equation claiming a number equals itself plus one.
Match data to operations
| Type | Meaning and example |
|---|---|
| Integer | Whole number, such as 17 |
| Real or float | Number that can have a fractional part, such as 21.5 |
| String | Text, such as "Lima" |
| Boolean | TRUE or FALSE |
| List or array | Ordered values, such as [18, 21, 19, 22, 20] |
Adding numeric 12 and 3 gives 15. Joining strings "12" and "3" gives "123". Choose descriptive names such as temperature and total so that the role of a value stays visible.
Arithmetic operators include +, −, *, and /. DIV gives the whole-number quotient, while MOD gives the remainder. Thus 17 DIV 5 is 3 and 17 MOD 5 is 2. The test n MOD 2 = 0 identifies an even integer. Comparisons such as =, ≠, <, >, ≤, and ≥ produce Boolean values.
Read, calculate, and display
INPUT minutes
hours ← minutes DIV 60
rest ← minutes MOD 60
OUTPUT hours, "h", rest, "min"
For 135 minutes, two complete groups of 60 use 120 minutes, leaving 15. The output is "2 h 15 min". INPUT receives data, the two assignments process it, and OUTPUT sends the result.
Preserve a value before replacing it
Suppose a holds 5 and b holds 8. The instructions a ← b and then b ← a leave both variables holding 8. The first instruction overwrote the only stored copy of 5.
Use a temporary variable:
temp ← a
a ← b
b ← temp
After the first line, temp holds 5. The second line puts 8 into a. The third puts the saved 5 into b. Assignment copies a current value; it does not create a permanent link between variables.
Give every variable a starting value before reading it. A running total needs total ← 0 before its first addition. Putting the assignment after the addition leaves the first step without a defined starting value.
Key Takeaways
- Pseudocode uses a consistent notation to express logic without choosing a programming language.
- Assignment evaluates the right side and replaces the stored value on the left.
- Data types affect which operations make sense.
DIVgives a whole-number quotient;MODgives a remainder.INPUTreceives data andOUTPUTsends a result.- A temporary variable preserves the old value during a swap.
- Initialize a variable before its value is used.
3.3 Choose the correct path with conditions
Selection chooses which instructions run. A condition is an expression with the value TRUE or FALSE. The comparison score ≥ 50 asks whether the current score is at least 50.
Use IF and ELSE
IF score ≥ 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
END IF
Exactly one branch runs. At 50, the condition is TRUE and the output is "Pass". At 49, it is FALSE and the output is "Fail". An IF without ELSE simply skips its block when its condition is FALSE.
The comparison must match the rule. “At least 50” includes 50, so it needs ≥. Using > would reject that boundary score. Testing values at the threshold is a direct way to catch this error.
Order several cases
An ELSE IF chain checks conditions in order and runs the first matching branch:
IF temperature ≥ 30 THEN
OUTPUT "Hot"
ELSE IF temperature ≥ 20 THEN
OUTPUT "Warm"
ELSE IF temperature ≥ 10 THEN
OUTPUT "Mild"
ELSE
OUTPUT "Cold"
END IF
For 24 °C, the first test fails and the second succeeds. The output is "Warm". For 10 °C, the third branch runs. For −3 °C, the final ELSE runs.
A temperature of 35 °C satisfies all three written comparisons, but only the first matching branch executes. If temperature ≥ 10 came first, it would catch 35 and output "Mild". When using overlapping “at least” thresholds, test the largest first. The lower branches then handle values that failed the higher thresholds.
Combine conditions
| Operator | When the result is TRUE |
|---|---|
A AND B | Both A and B are TRUE. |
A OR B | At least one of A and B is TRUE. |
NOT A | A is FALSE. |
To include temperatures from 10 °C up to, but not including, 20 °C, use temperature ≥ 10 AND temperature < 20. Both limits must hold. At 15, both are TRUE. At 20, the second is FALSE.
Using OR for this interval gives temperature ≥ 10 OR temperature < 20. That accepts every number: a value below 10 still satisfies the second part, while any value at least 10 satisfies the first. OR is useful when either route is enough, not when two limits must both hold.
Put a decision inside another decision
A nested IF puts one decision inside a branch of another. You might first check whether a password is long enough and then, within the successful branch, check whether it contains a digit. The inner decision is reached only when the outer condition permits it.
Indent the inner block so that the paths are visible. If several nested decisions make a simple rule hard to read, consider combining conditions with AND or using an ELSE IF chain. Trace a value through the actual order before assuming every written test is reached.
Key Takeaways
- A condition has a Boolean result: TRUE or FALSE.
IF … ELSEchooses one of two paths; anELSE IFchain chooses the first matching case.- Inclusive and exclusive thresholds need the matching comparison operator.
- AND requires both conditions, OR requires at least one, and NOT reverses a condition.
- Order overlapping thresholds so that an early branch does not swallow a later case.
- An inner decision runs only when execution reaches its containing branch.
3.4 Repeat work while keeping the right state
Iteration repeats a block of instructions. A loop lets you express repeated work once, but you still need to decide when it starts, when it ends, and which values change on each pass.
Choose how repetition is controlled
| Loop | How it runs |
|---|---|
FOR i ← 1 TO 5 | Runs five times, for 1 through 5 inclusive. |
FOR EACH item IN list | Runs once for each list item. |
WHILE condition DO | Checks before each pass; repeats while TRUE. |
REPEAT … UNTIL condition | Checks after each pass; stops when TRUE. |
A FOR loop suits a known repetition count. A condition-controlled loop suits a task whose stopping point depends on values or new input. A WHILE body may run zero times. A post-test REPEAT … UNTIL body runs at least once.
Trace a countdown
n ← 3
WHILE n > 0 DO
OUTPUT n
n ← n − 1
END WHILE
OUTPUT "Go!"
At the first test, n is 3. The loop outputs 3 and changes n to 2. The next passes output 2 and 1. After the update from 1 to 0, the test is FALSE. Execution leaves the loop and outputs "Go!".
Removing the update leaves n at 3, so the loop never reaches its stopping state. A loop intended to finish needs a way to change the condition: an internal update or fresh input can provide it.
Accumulate a total and count items
An accumulator builds a result over several passes. A counter records how often something occurs. To find the mean of daily temperatures 18, 21, 19, 22, and 20 °C:
total ← 0
count ← 0
FOR EACH t IN temperatures
total ← total + t
count ← count + 1
END FOR
OUTPUT total / count
The successive totals are 18, 39, 58, 80, and 100. The count ends at 5, so the mean is 20 °C. Initialize both variables before the loop. Resetting total inside it would erase the earlier additions. An empty list needs a separate check before division because its count is zero.
Remember the best value so far
For a nonempty list, start largest at the first item. Then inspect every value and replace largest whenever a larger value appears:
largest ← first item of list
FOR EACH value IN list
IF value > largest THEN
largest ← value
END IF
END FOR
OUTPUT largest
For [7, 3, 12, 5], the remembered best remains 7, becomes 12, and stays 12. Starting at zero fails for a list such as [−4, −9, −2], whose largest value is −2. Zero was never a candidate.
Check the first and last pass
An off-by-one error adds or loses one repetition. FOR i ← 0 TO 5 runs six times. In the countdown, n ≥ 0 would output zero too. Write out the first and last values of the control variable to check the count.
Nested loops repeat a loop inside another loop. For 3 rows and 4 columns, the inner block runs four times for each row, making 12 executions. The inner loop starts again for each outer pass.
Key Takeaways
- Count-controlled loops repeat a known number of times; condition-controlled loops depend on a test.
WHILEtests before the body, while pseudocodeREPEAT … UNTILtests afterward.- Initialize accumulators and counters before the loop, and update them inside it.
- A largest-value search can start from the first item of a nonempty list.
- A terminating loop needs a path to its stopping state.
- Check endpoints for off-by-one errors; an inclusive range from 0 through 5 has six values.
- An inner loop runs completely on each pass of its outer loop.
4Draw the paths and check the results
A diagram can reveal the paths through an algorithm, and a trace can reveal the values along one of those paths. Flowcharts and pseudocode describe the same logic in different forms. Moving between them helps expose misplaced tests and updates. Careful test data then checks ordinary cases, thresholds, and unusual inputs, while debugging uses a reproducible failure to locate the first step that needs repair.
4.1 Read a flowchart one arrow at a time
A flowchart draws an algorithm as shapes connected by arrows. The shapes identify kinds of steps, and the arrows show which step runs next. A short chart makes a process visible to someone who may not read code.
Choose a shape for each job
The main symbols follow ISO 5807. They have distinct jobs:
| Symbol | Shape | Job |
|---|---|---|
| Terminator | Oval or rounded rectangle | Marks Start or End. |
| Process | Rectangle | Performs an action or calculation. |
| Input/output | Parallelogram | Reads or sends data. |
| Decision | Diamond | Tests a condition or value and chooses one exit. |
| Predefined process | Rectangle with double vertical side lines | Calls a procedure described separately. |
| Connector | Small labeled circle | Joins separated portions of flow. |
A flow line has an arrow showing direction. The usual reading direction is top to bottom and left to right, but the arrow decides the actual next step. A line that returns to an earlier point can show repetition.
Build a simple sequence
To calculate a rectangular room's area, use these five symbols in order:
- Terminator: “Start.”
- Input/output: “Input length, width.”
- Process:
area ← length * width. - Input/output: “Output area.”
- Terminator: “End.”
Connect each step to the next with an arrow. With length 4.5 m and width 3 m, the calculation gives 13.5 square meters. Reading the input does not calculate the area; that belongs in its own process rectangle. Displaying the area belongs in the output parallelogram.
This chart has no choice or repeated path. It is a pure sequence, and its shape makes the order clear.
Follow a decision using current values
A diamond asks a question or tests a value. For a yes/no question such as score ≥ 50?, label the exits “Yes” and “No.” Work out the condition using the current score and follow exactly one matching arrow.
A decision can have more than two possible exits when it tests several distinct values. Label each exit with the value or case it represents. The purpose of the labels is to make the next step unambiguous.
An action such as count ← count + 1 belongs in a process rectangle. A question such as count < 5? belongs in a decision diamond. Mixing these jobs hides whether a value is being changed or tested.
Check the connections
A clear chart has one Start and at least one End. Every process and input/output symbol has one outgoing flow line. Every yes/no decision has two labeled exits. Follow every path to check that it reaches an intended next step or End.
Avoid leaving a branch floating after its output. If both branches should continue with the same step, draw them joining before that step. Use labeled connectors when long or crossing lines would make the page hard to follow. A predefined-process symbol lets a large procedure stay on a separate chart while the main chart keeps its overall shape.
Key Takeaways
- A flowchart uses shapes for kinds of steps and arrows for execution order.
- Rectangles perform actions, parallelograms handle data, and diamonds choose paths.
- Label decision exits and follow the arrow matching the current value.
- Use Start and End symbols and connect every intended path.
- A predefined-process symbol can hide the detail of a separate procedure.
4.2 Draw branches and loops without changing their logic
Pseudocode and flowcharts can express the same algorithm. Converting between them means preserving the order of actions, the conditions, and every route through the process. A neat diagram with a different test position describes a different algorithm.
Show a choice and rejoin the paths
For a pass mark of 50, draw a diamond labeled score ≥ 50?. Its Yes exit leads to an output parallelogram labeled “Pass.” Its No exit leads to one labeled “Fail.” Bring the paths together before End.
In pseudocode, these paths become the IF and ELSE branches. The point where they rejoin corresponds to the first instruction after END IF. The chart must not send the Pass output onward through the Fail output; only one of them belongs on any single run.
Put the test in the right place
A loop has a path back to an earlier step and a decision that controls whether repetition continues. For a WHILE loop, place the decision before the body. The FALSE exit bypasses the body, so zero passes are possible.
For a post-test REPEAT … UNTIL, place the decision after the body. Its FALSE exit returns to the body and its TRUE exit leaves the loop. The body runs at least once because execution reaches it before the first test.
| Loop | Position of decision | Exit from repetition |
|---|---|---|
WHILE condition | Before body | Condition is FALSE. |
REPEAT … UNTIL condition | After body | Condition is TRUE. |
Work through a three-attempt login
attempts ← 0
REPEAT
INPUT password
attempts ← attempts + 1
UNTIL password = storedPassword OR attempts = 3
IF password = storedPassword THEN
OUTPUT "Welcome"
ELSE
OUTPUT "Account locked"
END IF
Begin the chart with Start and a process rectangle for attempts ← 0. Next, draw the password input parallelogram, then the increment rectangle. The loop diamond asks “Password correct OR attempts = 3?” Its No exit returns to the password input. Its Yes exit leaves the loop.
The exit condition gives two possible reasons for stopping, so it cannot by itself choose the final message. Add a second diamond asking whether the password is correct. Yes leads to “Welcome”; No leads to “Account locked.” On a correct third attempt, the loop stops and the correct-password branch still welcomes the user.
Convert by following paths
From pseudocode to a chart, turn each assignment into a rectangle and each input or output into a parallelogram. Turn branch and loop tests into diamonds. Connect the body back to its controlling decision in the correct position.
From a chart to pseudocode, inspect where each diamond's paths lead. Paths that perform alternatives and rejoin suggest selection. A path that returns to earlier work suggests iteration. Indent each body to match its boundaries.
Check the destination of every backward arrow. Returning after the controlling decision would skip the next test. Returning before a one-time initialization could reset a counter on every pass and prevent the loop from finishing.
Key Takeaways
- Converting representations must preserve actions, conditions, and execution paths.
- Selection branches rejoin after their alternative work.
- Pre-test loops can skip the body; post-test loops run it at least once.
- A loop exit may need a separate decision to determine why the loop stopped.
- Backward arrows must return through the intended controlling test and avoid repeating one-time setup.
4.3 Find errors with traces and well-chosen tests
An algorithm can look reasonable while doing the wrong thing. Tracing follows its instructions exactly and records what happens. Testing runs it with chosen inputs and checks the results. Debugging finds and fixes the cause of a failure.
Make the state visible
A trace table records variables and outputs during a dry run. Use the current values, not the values you expect the author intended. For example:
total ← 0
FOR i ← 1 TO 4
total ← total + i
END FOR
OUTPUT total
| Point in execution | i | total | Output |
|---|---|---|---|
| After initialization | — | 0 | — |
| After first addition | 1 | 1 | — |
| After second addition | 2 | 3 | — |
| After third addition | 3 | 6 | — |
| After fourth addition | 4 | 10 | — |
| At OUTPUT | 4 | 10 | 10 |
This compact table shows the state after each addition. For a difficult bug, add rows after individual instructions and a column for condition results. A FALSE loop test belongs in a detailed trace too: it explains why execution leaves the loop.
Choose tests from the rules
Work out the expected result before running each test. Otherwise it is easy to accept the program's output simply because it appeared. Some tests check a property, such as keeping output in order, instead of one exact result.
For scores valid from 0 to 100 with a pass mark of 50:
| Kind | Example input | What it checks |
|---|---|---|
| Normal | 73 | A typical valid passing score. |
| Boundary | 0, 49, 50, 100 | Endpoints and the decision threshold. |
| Just outside the range | −1, 101 | Rejection beyond valid endpoints. |
| Invalid type | "abc" | Rejection of text where a score is needed. |
Boundary and invalid categories can overlap: −1 is both near a boundary and invalid. The category explains why the test is useful. A rule using score > 50 passes normal tests at 73 and 49 but fails at exactly 50.
Test unusual input structures too. An empty list, one item, all equal values, and negative values expose different assumptions. A mean algorithm must handle an empty list before dividing by its count. A largest-value algorithm initialized to zero can fail on an all-negative list.
Identify the error you are fixing
A syntax error breaks a language's writing rules, such as a missing closing parenthesis. A runtime error occurs during execution, such as division by zero. A logic error permits execution but gives a wrong result, such as excluding the passing boundary with >.
These categories help you choose a check. Syntax checking catches broken language forms. A trace can reveal the first wrong state in a logic error. Test data can trigger a runtime failure that a typical input never reaches.
Debug from the first mismatch
Reproduce the failure with a specific input. Trace or display intermediate values and find the first step where the actual state differs from the expected state. Change the cause, then rerun the failing test and the earlier tests. A repair to one branch can break another.
Passing selected tests gives evidence about those inputs. Correctness still requires the method to handle every valid input, so combine testing with reasoning about the instructions and their assumptions.
Key Takeaways
- A trace records what instructions actually do, using current variable values.
- Choose expected results or required properties before running tests.
- Use normal, boundary, invalid, and structural edge cases.
- Syntax errors break language rules, runtime errors occur during execution, and logic errors produce wrong behavior.
- Locate the first wrong state, fix its cause, and rerun earlier tests.
- Passing a collection of tests gives evidence without establishing correctness for every valid input.
5Build and coordinate programs in Scratch
Blocks give instructions a visible shape so that you can build and run a program while concentrating on its logic. Scratch introduces that model through sprites, events, variables, decisions, and loops. Short projects connect input to visible output, and custom blocks turn repeated work into named procedures. Coordinating several scripts also shows why the order within one script differs from the timing between scripts.
5.1 Build a script from Scratch blocks
In block-based programming, graphical blocks stand for instructions and values. You drag them into a workspace and snap them together. The shapes remove much of the work of remembering syntax, leaving you free to concentrate on the program's logic.
Know the parts of a project
Scratch was created at the MIT Media Lab. Other block environments include Snap!, developed at the University of California, Berkeley, Microsoft MakeCode, and Blockly. Blockly is a library for building block interfaces; it began at Google and moved to the Raspberry Pi Foundation in 2025.
In Scratch, the stage is the area where the project runs visibly. Sprites are characters or objects that act on it. A sprite can have scripts, costumes, and sounds. A script is a stack of blocks; a costume is an image the sprite can display.
The stage is 480 by 360 Scratch units. Its center is the coordinate point (0, 0). Horizontal x-coordinates run from −240 to 240, and vertical y-coordinates from −180 to 180. Scratch movement steps are stage units, not meters.
Let the block shape guide you
| Block shape | Role | Example |
|---|---|---|
| Hat | Starts a script in response to an event. | "when green flag clicked" |
| Stack | Performs one command. | "move 10 steps" |
| C-shaped | Wraps blocks in a loop or branch. | "repeat 10" |
| Rounded reporter | Supplies a value. | A variable's value block |
| Six-sided Boolean | Supplies TRUE or FALSE. | "touching mouse-pointer?" |
| Cap | Ends a script. | "stop all" |
A value reporter fits inside an input slot of another block. A command fits in a stack of actions. A Boolean fits a condition slot. Shape helps distinguish giving a value from carrying out a command.
Find blocks by category
Scratch 3 has nine main color-coded categories: Motion, Looks, Sound, Events, Control, Sensing, Operators, Variables, and My Blocks. Motion changes position; Looks handles visible appearance and speech; Sensing receives information; Operators calculate or compare. The Pen extension is added separately when a project needs to draw lines as a sprite moves.
Run a short sequence
Select a sprite and place these blocks under a “when green flag clicked” hat:
- “go to x: 0 y: 0”
- “say Hello! for 2 seconds”
- “move 100 steps”
Click the green flag. The sprite first goes to the center, then displays "Hello!" for two seconds, then moves 100 steps in its current direction. The timed speech block makes the pause visible. The stack runs from top to bottom.
A loose stack can run when clicked directly in the workspace, but it will not start from the green flag unless it has the matching event hat. Check both the stack's order and its starting event when the project seems unresponsive.
Correctly fitting blocks still need a correct plan. A move can happen before an intended position reset, or a question can be asked after the result is displayed. Shapes help with valid construction; tracing reveals whether that construction does the intended work.
Key Takeaways
- Blocks express instructions and values with shapes that guide their placement.
- The stage displays the project; sprites have their own scripts, costumes, and sounds.
- A script runs from its starting event through the stack in order.
- Scratch’s center is (0, 0), with a stage 480 by 360 units.
- Use categories to find blocks and add extensions such as Pen when needed.
- A fitting block arrangement can still contain a logic error.
5.2 Make a block program respond and repeat
Scratch uses the same ideas as pseudocode: store a value, test a condition, and repeat steps. The blocks make the structure visible, but their position still determines when each action happens.
Pick a loop that fits the task
“Repeat 10” runs its body ten times. “Forever” keeps running until the program stops and suits a game that continually checks input. “Repeat until ” tests before every pass and stops when the condition is true. It can therefore run zero times, unlike the post-test pseudocode REPEAT … UNTIL.
With the Pen extension and the pen down, “repeat 4” containing “move 100 steps” and “turn right 90 degrees” draws a square. For a regular hexagon, use six repetitions and a 60-degree turn. The direction changes add up to 360 degrees around the shape.
Store a value and choose a branch
Create score in Variables. “Set score to 0” assigns its starting value. “Change score by 1” adds to its current value. Put the reset before a scoring loop; inside it, the reset would erase the earlier score every time.
The rounded score reporter supplies the current value to other blocks. Checking its box shows a monitor on the stage, which helps while tracing.
An “if … then … else” block runs one of its two bodies. Its six-sided condition slot accepts a Boolean such as “(score) > (9)” or “touching mouse-pointer?”. Operators “and,” “or,” and “not” combine conditions with the same meanings as in pseudocode.
Receive input, build text, and show it
The block “ask [What is your name?] and wait” pauses for input and stores it in “answer.” The block “join [Hello, ] (answer)” builds text. Put that reporter inside “say … for 2 seconds” to display the greeting. If the input is "Amara", the output is "Hello, Amara".
The three roles are separate: ask receives data, join processes text, and say displays it. A reporter can calculate a useful value without showing anything on its own.
Build a guessing game
Use this block order, with each indented part inside its containing block:
"when green flag clicked"
"set secret to (pick random 1 to 10)"
"ask [Guess a number from 1 to 10] and wait"
"repeat until <(answer) = (secret)>"
"if <(answer) > (secret)> then"
"say [Too high] for 2 seconds"
"else"
"say [Too low] for 2 seconds"
"ask [Guess a number from 1 to 10] and wait"
"say [Correct!] for 2 seconds"
A correct first guess skips the loop. For secret 6 and guesses 3, 8, and 6, the feedback is "Too low", "Too high", then "Correct!". The new ask inside the loop supplies a value that can make its condition true.
Timed feedback matters. A visible sprite's ask question uses its speech bubble, so the next ask immediately replaces an untimed say bubble. A two-second say lets the learner read the feedback first.
Read the loop as WHILE answer ≠ secret to check it in pseudocode. Omitting the repeated ask traps the game with the old incorrect answer; moving the final success message inside the loop puts it on the wrong path.
Key Takeaways
- Scratch “repeat until” checks before each pass and can skip its body.
- Initialize a score before a loop and update it inside the loop.
- A Boolean reporter supplies the condition for a decision.
- Ask reads input, join builds text, and say displays text.
- A guessing loop needs new guesses so that it can reach its stopping condition.
- Timed say blocks keep feedback visible before a new ask replaces the bubble.
5.3 Coordinate scripts and reuse a custom block
A Scratch project often has several scripts waiting for different events. Event-driven programming starts a script when an event occurs. A custom block then lets a script call a named piece of reusable work.
Start the right script
Hat blocks include “when green flag clicked,” “when this sprite clicked,” “when space key pressed,” and “when I receive [message].” Each describes what starts its attached stack.
Several scripts can respond to the same event. Two sprites can both start when the green flag is clicked and then run alongside one another. The position of their stacks on the workspace does not establish an execution order between them.
Within one script, actions remain ordered from top to bottom. Across scripts, timing can matter. If two scripts both move the same sprite in opposite directions, their combined result depends on when their actions run. Give scripts clear responsibilities and coordinate work when one job needs another's result.
Send a message between scripts
“Broadcast [game over]” sends a message to all sprites and the stage. Matching “when I receive [game over]” scripts start in response. The message name must match; it identifies the event that receivers handle.
“Broadcast and wait” also pauses the sender until the receiving scripts finish. Use it when the next action depends on their completion. For example, a controller can broadcast a setup message and wait while sprites move to starting positions, then begin the game.
Waiting does not order the receivers among themselves. If two setup receivers both overwrite the same value, they still need a plan that avoids conflicting responsibilities. A receiver that runs forever also prevents the waiting sender from continuing.
Give repeated work a name and an input
In My Blocks, make a custom block with an input called size. Its definition can be described as:
"define square (size)"
"repeat 4"
"move (size) steps"
"turn right 90 degrees"
With the pen down, calling “square (100)” draws sides of 100 steps. Calling “square (60)” uses the same instructions with shorter sides. The custom block provides abstraction by hiding the steps behind a name and generalization by letting the caller supply the size.
The call runs the definition; it does not copy a second hand-maintained version into the script. Changing the definition changes the work performed by later calls. This makes a repeated method easier to maintain.
Carry the ideas into text
| Scratch idea | Pseudocode or text-code idea |
|---|---|
| "repeat 4" | Count-controlled loop |
| "if … then … else" | Selection |
| "set score to 0" | Assignment |
| Custom block | Procedure |
| Event hat and attached script | Event handler |
In a text-based language, you type the instructions and obey the language's punctuation and spacing rules. The underlying reasoning about state, conditions, and repetition continues to apply.
Blocks remove many syntax mistakes, but the wrong condition can still choose the wrong path. Traces and tests remain useful. Large block projects can also become hard to navigate and compare because their scripts take up substantial screen space; text is easier to search and manage for large software projects.
Key Takeaways
- An event starts the scripts whose hats respond to it.
- Scripts can run concurrently, so workspace position does not set their order.
- Broadcast starts matching receivers; broadcast and wait also waits for their completion.
- Custom blocks hide reusable steps and can take parameters.
- The same logic of assignment, selection, iteration, and procedures carries into text-based code.
Computational Thinking and Problem Solving examples
1From a task to a checkable solution
10 steps
- 1IntroductionStart with the result
A clear problem is easier to solve than a vague request. Suppose a reading group wants its members’ names displayed alphabetically. Before choosing software, identify what information is available and what the finished result must contain.
You will follow that request from a problem statement to a plan, using input, process, output, and the four techniques of computational thinking.
- 2ExplanationName the input and output
The input is the list of members’ names. The required output is the same list in alphabetical order. The process is the method that rearranges the names.
These roles are different. A list with a missing member fails the task even if the remaining names are ordered. Specifying the output gives you a way to recognize that failure before deciding how the method works.
- 3ConnectionPlace the task within computer science
Computer science studies information and the processes that handle it. This task raises questions about representing names, designing a method, and checking that the result is correct.
Programming would express instructions in an executable language. The wider questions come first: what output is required, what assumptions does the method need, and how much work will a larger list create?
- 4ChallengeCheck a proposed output
The input names are "Noor", "Ava", and "Luis". A system displays "Ava", "Noor". What requirement has it failed, even before you discuss its speed?
---reveal---
It failed to preserve every input name: Luis is missing. Alphabetical order alone is not the full output requirement. The result must contain the original names and put them in the required order.
- 5ExplanationChoose tools for thinking
Four techniques help turn the request into a solution. Decomposition separates collecting names, arranging them, and displaying the result. Pattern recognition finds repeated work across names. Abstraction keeps the information the task needs. Algorithm design specifies the instructions.
You can revisit any technique when a check reveals a problem. Their names describe kinds of thinking, not a fixed four-step execution sequence.
- 6ExampleMake the requirements usable
Write the inputs, outputs, constraints, and success criteria. For the reading group, the input is its member list and the output is an ordered display. Keeping every name is a requirement; checking the count and membership helps judge the result.
Then make a plan, express it, and test it. These actions follow Pólya’s stages: understand, plan, carry out, and look back. A test can expose something the first plan missed.
- 7AnalogyUse the same thinking for meals
Planning meals uses the same approach. Split choosing recipes from making the shopping list. Notice shared ingredients, keep relevant quantities, then order the actions: combine needs, check existing food, and shop.
The representation “rice, 1 kg” keeps a useful quantity without preserving an irrelevant brand. The purpose decides which details matter; cooking for more people changes the quantities the plan needs.
- 8ChallengeChoose the first useful action
An organizer says, “Make the event schedule better.” A developer starts designing a colorful display. What should the team clarify before that implementation choice?
---reveal---
Clarify the available information, the required result, and the constraints. For example, ask what “better” means and how success will be checked. A polished display can execute a plan that never addressed the scheduling problem.
- 9ChallengeConnect the plan to the check
A tool combines ingredient lists but counts the same cupboard stock once for every recipe that uses it. The final shopping quantity is too small. Which part of the ordered method needs investigation, and why?
---reveal---
Investigate how shared needs are combined and existing stock is subtracted. The cupboard stock should be accounted for against the combined requirement. The failed output points back to the processing steps, even though the ingredient data may have been entered correctly.
- 10RecapCarry a clear problem into the next step
A useful starting brief names its inputs, required outputs, constraints, and checks. The solution can then be divided, simplified, expressed, and revised.
For your next task, write one concrete success criterion before choosing a method. It should let another person judge the result without needing to know which software or language produced it.
2Build a small model of a larger task
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake a quiz manageable
- 2ExplanationStart with responsibilities
- 3ExampleRefine one branch
- 4TipWrite the handoffs
- 5ChallengeFind a gap in the plan
- 6ExplanationLook for the same work
- 7ExampleGeneralize a drawing method
- 8ChallengeCheck whether reuse is justified
- 9AnalogyKeep the map’s purpose in view
- 10ExampleName a job and hide its steps
- 11ChallengeSelect data for the purpose
- 12ChallengeCombine the three techniques
- 13RecapInspect the boundaries you chose
3Trace a complete algorithm from input to output
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow what the instructions actually do
- 2ExplanationMake the method complete
- 3ExampleCompare work on ordered pages
- 4ChallengeTest the method’s assumption
- 5ExplanationRead assignment as replacement
- 6ExamplePreserve the old value in a swap
- 7ChallengeSplit a duration into groups and remainder
- 8ExplanationChoose one path
- 9ExampleRequire both limits
- 10ChallengeOrder overlapping tests
- 11ExplanationDecide when the loop tests
- 12ExampleSet up a running mean
- 13ExampleTake the first two passes
- 14ExampleFinish the mean calculation
- 15TipCheck progress and endpoints
- 16ExampleStart the best value with a candidate
- 17ChallengeTrace before the next test
- 18ConnectionRepeat a loop for each row
- 19ChallengeCombine selection and accumulation
- 20RecapUse a trace to defend the result
4Follow a flowchart and repair a boundary error
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSee both the path and the values
- 2ExplanationMatch shapes to actions
- 3ExampleDraw the area sequence
- 4ChallengeChoose the missing symbol
- 5ExplanationTurn a branch into IF
- 6ExamplePlace a WHILE decision first
- 7ExamplePlace a login test after input
- 8ChallengeFollow a successful last attempt
- 9ExplanationRecord current state
- 10ExampleWrite expectations before running
- 11TipChoose different kinds of test input
- 12ChallengeFind the first wrong update
- 13ExplanationRepair the cause and check again
- 14ChallengeUse a trace and a new test together
- 15RecapLet each check answer a question
5Build an interactive Scratch program
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionConnect a plan to visible behavior
- 2ExplanationChoose the sprite and starting event
- 3ExampleRun a short stack in order
- 4ChallengeDistinguish a value from an action
- 5ExplanationInitialize before repeated work
- 6ExampleReceive input and produce output
- 7ExampleChoose the secret and ask once
- 8ExampleGive readable feedback
- 9ExampleFollow three guesses
- 10ChallengeCompare the two until forms
- 11ExplanationCoordinate a dependent script
- 12ChallengeCheck what completion requires
- 13ExampleMake one drawing procedure
- 14ConnectionCarry the structure into text
- 15TipGive shared state a clear owner
- 16ChallengeCombine setup, repetition, and reuse
- 17RecapRead the behavior as an algorithm
Computational Thinking and Problem Solving practice questions
Set 1: Define a problem and build a plan10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
What values remain after this pseudocode?
a ← 6
b ← 11
a ← b
b ← a
Show answerHide answer
a, replacing its previous 6. The final line reads that current value of a, so it copies 11 into b too. A swap would need to save the original 6 in a temporary variable before overwriting a; assignment does not preserve old values by itself.Set 2: Follow variables, decisions, and loops10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What is output for load = 82?
IF load ≥ 80 THEN
OUTPUT "High"
ELSE IF load ≥ 50 THEN
OUTPUT "Medium"
ELSE
OUTPUT "Low"
END IF
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
How many times does the output run?
FOR i ← 2 TO 6
OUTPUT i
END FOR
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What sequence is output?
n ← 5
WHILE n > 0 DO
n ← n − 2
OUTPUT n
END WHILE
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What is output?
total ← 0
FOR EACH n IN [2, 5, 6, 9]
IF n MOD 2 = 0 THEN
total ← total + n
END IF
END FOR
OUTPUT total
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
248 DIV 60 and 248 MOD 60 give, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What does this output?
value ← 7
value ← value + 4
OUTPUT value
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
largest ← 0 and replaces it only when a larger item appears. What single change makes its starting value valid for every such list?Show answerHide answer
Save this lesson to see this answer.
Set 3: Read flowcharts and investigate failures10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
> where the rule needs ≥. What kind of error is this?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
distance ← speed * time?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
count = 0?. For count 3, where should execution go next?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
items > 0? before a repeated body. Yes enters the body and returns to the test; No goes to End. What pseudocode structure matches it?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What are the successive stored totals after each body execution?
total ← 1
FOR i ← 1 TO 3
total ← total * 2
END FOR
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
temperature > −8 AND temperature ≤ 12. Tests at −9, 0, 12, and 13 pass. What new test exposes the defect, and what should its expected result be?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
total ← 0, then inputs a value, adds it to total, and tests whether another value is needed. Its Yes arrow returns to initialization. The goal is a running total. Where should that Yes arrow return?Show answerHide answer
Save this lesson to see this answer.
Set 4: Build and coordinate Scratch scripts10 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
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
score is set to 0 before "repeat 6". Inside the repeat body, "set score to 0" is followed by "change score by 2". What score remains?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
done is already TRUE before a "repeat until " block. How many times does its body run?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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.
Set 5: Apply the ideas in new situations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What pair is output?
a ← 9
b ← 14
temp ← a
a ← b + 1
b ← temp
OUTPUT a, b
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
(mass ≥ 2 AND mass ≤ 5) OR readable. What erroneous acceptance can occur?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What is output?
total ← 0
count ← 0
FOR EACH n IN [−3, 4, 0, 8, −1]
IF n > 0 THEN
total ← total + n
count ← count + 1
END IF
END FOR
OUTPUT total / count
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
n ← 0, then repeats n ← n + 2 until n ≥ 5, and outputs n. A flowchart is drawn with the same condition before the body: Yes goes to output, No enters the body and returns. For this input both output 6. What change exposes their different loop behavior?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
Abstraction
Abstraction layer
Accumulator
Algorithm
Answer reporter
Assignment
count ← count + 1, the old count is read before the new value is placed back into count.B
Block-based programming
Boolean
score ≥ 50 supplies a Boolean that decides which branch of the algorithm runs.Boolean block
Boundary test
Branch
Broadcast
C
Computation
Computational thinking
Computer engineering
Computer science
Concurrency
Condition
remaining > 0 decides whether another item should be processed by the loop.Condition-controlled loop
Connector
Constant
Constraint
Control structure
Correctness
Count-controlled loop
Counter
Custom block
D
Data science
Data type
Debugging
Decision symbol
score ≥ 50? sends a qualifying score along Yes and a lower score along No.Decomposition
Decomposition diagram
Dependency
DIV
135 DIV 60 identifies two complete hours before the remaining minutes are handled.Dry run
E
ELSE IF chain
Event
Event handler
F
Flow line
Flowchart
Forever block
G
Generalization
H
Hat block
I
Infinite loop
Information technology
Input
Input/output symbol
Integer
Iteration
J
Join block
L
List
Logic error
Logical operator
M
MOD
135 MOD 60 gives the 15 minutes left after two complete hours have been removed.Model
N
Nesting
O
Off-by-one error
n ≥ 0 outputs zero as well as the positive values if that body outputs n.Output
P
Parameter
Pattern recognition
Post-test loop
Pre-test loop
Predefined process
Problem-solving cycle
Procedure
Process symbol
area ← length * width calculates a value after the two measurements have been read.Program
Programming
Pseudocode
R
Real-valued data
Repeat block
Repeat-until block
Reporter block
Return value
Runtime error
S
Script
Selection
Sequence
Sprite
Stage
String
Subproblem
Success criterion
Syntax error
T
Terminator
Top-down decomposition
Trace table
Trend
V
Variable
- 1Computational Thinking and Problem Solving
- 2Binary and Data Representation
- 3How Computers Work
- 4Searching, Sorting and Efficiency
- 5Programming Languages and Paradigms
- 6How the Internet Works
- 7Computing Ethics
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.