Computational Thinking and Problem Solving

Learn how computer scientists approach problems. Find out what computer science studies, then practice the four techniques of computational thinking: breaking a problem into parts, spotting patterns, keeping only the details that matter, and writing a precise step-by-step solution. Write algorithms in pseudocode with variables, decisions and loops, draw them as flowcharts, check them with trace tables and test data, and build your first programs from blocks in Scratch.

BeginnerLesson 1 of 7 in Introduction to Computer Science Course

What you will learn

  1. 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 studies
      Explain 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 techniques
      Define computational thinking, name decomposition, pattern recognition, abstraction and algorithm design, and use them together in a problem-solving process.
  2. 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 parts
      Break a problem into subproblems, organize them in a hierarchy, and decide when a part is small enough to solve directly.
    • Recognize patterns and generalize solutions
      Find 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 matters
      Keep the details a purpose needs, hide the rest, and use models and named procedures as abstractions with clear inputs and outputs.
  3. 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 good
      Define 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 output
      Write pseudocode that reads input, stores and updates values in variables, calculates with operators and produces output.
    • Make decisions with selection
      Write 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 loops
      Use count-controlled and condition-controlled loops, keep running totals and counts, and avoid infinite loops and off-by-one errors.
  4. 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 flowcharts
      Use 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 pseudocode
      Draw selection and iteration in flowcharts and translate an algorithm in either direction between flowchart and pseudocode.
    • Trace, test and debug an algorithm
      Check an algorithm by hand with a trace table, choose normal, boundary and invalid test data, and find and fix the three kinds of errors.
  5. 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 environment
      Explain 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 blocks
      Use 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 code
      Start scripts with events, coordinate sprites with messages, define custom blocks with inputs, and carry the same ideas over to text-based languages.

Computational Thinking and Problem Solving study guide

5 chapters

1

What 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.

AreaA question it studies
Algorithms and theoryWhat steps solve a problem, and what can be computed?
Programming languagesHow can instructions be expressed clearly?
Computer systemsHow do hardware, operating systems, and networks support computation?
Data and databasesHow can information be stored, organized, and retrieved?
Artificial intelligence and machine learningHow can systems perform tasks such as recognizing patterns?
Human–computer interactionHow can people understand and use a system?
SecurityHow can data and systems be protected?
Computer graphicsHow can images be created and displayed?
Software engineeringHow 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:

  1. Understand the problem. Identify inputs, outputs, constraints, and success criteria.
  2. Make a plan. Choose smaller tasks, useful patterns, and an algorithm.
  3. Carry out the plan. Express and execute it with pseudocode, a flowchart, or a program.
  4. 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.
2

Break 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:

turn angle=360∘/n

Here, n is the number of sides. Repeat the move-and-turn pair n times, keeping the same side length and turn each time.

Regular polygonSidesTurn at each corner
Triangle3120°
Square490°
Pentagon572°
Hexagon660°

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:

PurposeDetails the model needs
Racing gameSpeed, position, and direction
Parking-garage systemLicense 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.
3

Express 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:

StructureWhat happens
SequenceSteps run one after another.
SelectionA condition chooses a path.
IterationA 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
TypeMeaning and example
IntegerWhole number, such as 17
Real or floatNumber that can have a fractional part, such as 21.5
StringText, such as "Lima"
BooleanTRUE or FALSE
List or arrayOrdered 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.
  • DIV gives a whole-number quotient; MOD gives a remainder.
  • INPUT receives data and OUTPUT sends 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
OperatorWhen the result is TRUE
A AND BBoth A and B are TRUE.
A OR BAt least one of A and B is TRUE.
NOT AA 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 … ELSE chooses one of two paths; an ELSE IF chain 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
LoopHow it runs
FOR i ← 1 TO 5Runs five times, for 1 through 5 inclusive.
FOR EACH item IN listRuns once for each list item.
WHILE condition DOChecks before each pass; repeats while TRUE.
REPEAT … UNTIL conditionChecks 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.
  • WHILE tests before the body, while pseudocode REPEAT … UNTIL tests 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.
4

Draw 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:

SymbolShapeJob
TerminatorOval or rounded rectangleMarks Start or End.
ProcessRectanglePerforms an action or calculation.
Input/outputParallelogramReads or sends data.
DecisionDiamondTests a condition or value and chooses one exit.
Predefined processRectangle with double vertical side linesCalls a procedure described separately.
ConnectorSmall labeled circleJoins 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:

  1. Terminator: “Start.”
  2. Input/output: “Input length, width.”
  3. Process: area ← length * width.
  4. Input/output: “Output area.”
  5. 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.

LoopPosition of decisionExit from repetition
WHILE conditionBefore bodyCondition is FALSE.
REPEAT … UNTIL conditionAfter bodyCondition 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 executionitotalOutput
After initialization—0—
After first addition11—
After second addition23—
After third addition36—
After fourth addition410—
At OUTPUT41010

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:

KindExample inputWhat it checks
Normal73A typical valid passing score.
Boundary0, 49, 50, 100Endpoints and the decision threshold.
Just outside the range−1, 101Rejection 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.
5

Build 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 shapeRoleExample
HatStarts a script in response to an event."when green flag clicked"
StackPerforms one command."move 10 steps"
C-shapedWraps blocks in a loop or branch."repeat 10"
Rounded reporterSupplies a value.A variable's value block
Six-sided BooleanSupplies TRUE or FALSE."touching mouse-pointer?"
CapEnds 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:

  1. “go to x: 0 y: 0”
  2. “say Hello! for 2 seconds”
  3. “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 ideaPseudocode or text-code idea
"repeat 4"Count-controlled loop
"if … then … else"Selection
"set score to 0"Assignment
Custom blockProcedure
Event hat and attached scriptEvent 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

5 Walkthroughs

1

From a task to a checkable solution

10 steps
Identify a computation, define its result, and use the four thinking techniques to plan a solution.
  1. 1
    IntroductionStart 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.

  2. 2
    ExplanationName 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.

  3. 3
    ConnectionPlace 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?

  4. 4
    ChallengeCheck 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.

  5. 5
    ExplanationChoose 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.

  6. 6
    ExampleMake 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.

  7. 7
    AnalogyUse 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.

  8. 8
    ChallengeChoose 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.

  9. 9
    ChallengeConnect 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.

  10. 10
    RecapCarry 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.

2

Build a small model of a larger task

13 steps
Split a quiz into responsibilities, reuse shared methods, and choose the details each part needs.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake a quiz manageable
  2. 2
    ExplanationStart with responsibilities
  3. 3
    ExampleRefine one branch
  4. 4
    TipWrite the handoffs
  5. 5
    ChallengeFind a gap in the plan
  6. 6
    ExplanationLook for the same work
  7. 7
    ExampleGeneralize a drawing method
  8. 8
    ChallengeCheck whether reuse is justified
  9. 9
    AnalogyKeep the map’s purpose in view
  10. 10
    ExampleName a job and hide its steps
  11. 11
    ChallengeSelect data for the purpose
  12. 12
    ChallengeCombine the three techniques
  13. 13
    RecapInspect the boundaries you chose
3

Trace a complete algorithm from input to output

20 steps
Build a small list-processing method while practicing assignment, selection, loops, and termination.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow what the instructions actually do
  2. 2
    ExplanationMake the method complete
  3. 3
    ExampleCompare work on ordered pages
  4. 4
    ChallengeTest the method’s assumption
  5. 5
    ExplanationRead assignment as replacement
  6. 6
    ExamplePreserve the old value in a swap
  7. 7
    ChallengeSplit a duration into groups and remainder
  8. 8
    ExplanationChoose one path
  9. 9
    ExampleRequire both limits
  10. 10
    ChallengeOrder overlapping tests
  11. 11
    ExplanationDecide when the loop tests
  12. 12
    ExampleSet up a running mean
  13. 13
    ExampleTake the first two passes
  14. 14
    ExampleFinish the mean calculation
  15. 15
    TipCheck progress and endpoints
  16. 16
    ExampleStart the best value with a candidate
  17. 17
    ChallengeTrace before the next test
  18. 18
    ConnectionRepeat a loop for each row
  19. 19
    ChallengeCombine selection and accumulation
  20. 20
    RecapUse a trace to defend the result
4

Follow a flowchart and repair a boundary error

15 steps
Translate a short process, track its values, and choose tests that distinguish correct and incorrect behavior.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSee both the path and the values
  2. 2
    ExplanationMatch shapes to actions
  3. 3
    ExampleDraw the area sequence
  4. 4
    ChallengeChoose the missing symbol
  5. 5
    ExplanationTurn a branch into IF
  6. 6
    ExamplePlace a WHILE decision first
  7. 7
    ExamplePlace a login test after input
  8. 8
    ChallengeFollow a successful last attempt
  9. 9
    ExplanationRecord current state
  10. 10
    ExampleWrite expectations before running
  11. 11
    TipChoose different kinds of test input
  12. 12
    ChallengeFind the first wrong update
  13. 13
    ExplanationRepair the cause and check again
  14. 14
    ChallengeUse a trace and a new test together
  15. 15
    RecapLet each check answer a question
5

Build an interactive Scratch program

17 steps
Use events, state, input, feedback, loops, and custom blocks while keeping scripts coordinated.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionConnect a plan to visible behavior
  2. 2
    ExplanationChoose the sprite and starting event
  3. 3
    ExampleRun a short stack in order
  4. 4
    ChallengeDistinguish a value from an action
  5. 5
    ExplanationInitialize before repeated work
  6. 6
    ExampleReceive input and produce output
  7. 7
    ExampleChoose the secret and ask once
  8. 8
    ExampleGive readable feedback
  9. 9
    ExampleFollow three guesses
  10. 10
    ChallengeCompare the two until forms
  11. 11
    ExplanationCoordinate a dependent script
  12. 12
    ChallengeCheck what completion requires
  13. 13
    ExampleMake one drawing procedure
  14. 14
    ConnectionCarry the structure into text
  15. 15
    TipGive shared state a clear owner
  16. 16
    ChallengeCombine setup, repetition, and reuse
  17. 17
    RecapRead the behavior as an algorithm

Computational Thinking and Problem Solving practice questions

50 Practice Questions in 5 sets

Set 1: Define a problem and build a plan10 Practice Questions

Question 1 of 10

A system receives a list of measured masses, calculates their mean, and displays one value in kilograms. What is its output?
  1. The input list of masses.
  2. The displayed mean mass.
  3. The steps for the mean.
  4. The number of steps used.
Show answerHide answer
Answer: B
The output is the result the process sends out: the mean mass in kilograms. The measurements are the input from which that result is calculated. Confusing them reverses the direction of the computation; the steps for calculating a mean describe the process itself.

Question 2 of 10

An organizer asks for a program to arrange workshop names alphabetically. What requirement would let someone check its result?
  1. The program displays a list with shorter names near the top.
  2. The program uses a loop to inspect each submitted workshop name.
  3. The output contains the ten names most often requested by visitors.
  4. The output contains every original name in alphabetical order.
Show answerHide answer
Answer: D
A checkable requirement specifies the required output: all the original names, ordered alphabetically. Requiring a loop chooses part of a method without establishing whether the result is correct. Omitting names would fail the task even if the remaining names were in order.

Question 3 of 10

Before designing a program for room bookings, a team lists the available information, required result, and rules against double booking. What problem-solving stage is this?
  1. Understanding the problem.
  2. Carrying out the algorithm.
  3. Debugging the implementation.
  4. Comparing execution speeds.
Show answerHide answer
Answer: A
The team is defining inputs, outputs, and constraints, which belongs to understanding the problem. It has not yet chosen instructions that can be executed. Debugging would require behavior to investigate; listing the booking rules establishes what correct behavior must be.

Question 4 of 10

A parcel system is split into reading requests, choosing routes, and printing route labels. Labels must show the chosen route. What dependency must its plan preserve?
  1. Choosing a route must precede printing its label.
  2. Printing a label must precede reading its request.
  3. Reading requests must wait for all labels to print.
  4. Choosing routes must wait until labels are printed.
Show answerHide answer
Answer: A
Printing needs the route choice as input, so route selection must happen first for that parcel. Reversing those tasks would leave the label step without its required value. Splitting the system into separate parts helps only when the plan also preserves their dependencies.

Question 5 of 10

A designer keeps dividing a task into smaller parts. When is it reasonable to stop refining one part?
  1. When every main branch has been refined to the same depth.
  2. When the part has a name but its method remains unknown.
  3. When its solution is clear or an existing tool handles it.
  4. When its inputs are listed but its output is still undefined.
Show answerHide answer
Answer: C
Refinement can stop once a part is directly solvable or already handled by a known solution. Equal numbers of branches do not make a decomposition better. The useful boundary is determined by the work and the available methods, so different branches can need different depths.

Question 6 of 10

A drawing method repeats eight equal moves and equal right turns to make a regular octagon. What turn is needed after each move?
  1. 135 degrees.
  2. 45 degrees.
  3. 60 degrees.
  4. 90 degrees.
Show answerHide answer
Answer: B
The direction changes must total one complete revolution, so each of the eight turns is 360∘/8=45∘. Using 135 degrees confuses the octagon’s interior angle with the change in direction. The repeated turn is measured between the old and new directions of travel.

Question 7 of 10

A delivery model keeps road connections and street lengths but removes one-way restrictions. It sometimes proposes a drive against permitted traffic. What should be changed?
  1. Remove street lengths from routing.
  2. Keep only the start and end street names.
  3. Split streets into equal-length pieces.
  4. Keep one-way restrictions in the model.
Show answerHide answer
Answer: D
A driving model needs permitted travel directions because they affect which routes are usable. Abstraction should remove details irrelevant to the purpose, not a rule that changes the answer. More geometric detail would not restore the missing permission information.

Question 8 of 10

Three programs find the lightest package, shortest recording, and lowest temperature in nonempty lists. What reusable method fits all three?
  1. Remember zero, then replace it whenever a smaller value appears.
  2. Compare only the first and last values and return the smaller one.
  3. Remember the first value, then replace it whenever a smaller value appears.
  4. Return the value halfway between the first and last listed values.
Show answerHide answer
Answer: C
All three tasks seek a minimum, so the best-so-far method transfers between them. Starting with the first value makes the stored result an actual candidate; starting with zero fails when every value is positive. Inspecting every remaining value also handles a minimum in the middle.

Question 9 of 10

A set of instructions says “repeat the check” but gives no stopping rule or finite count. What algorithm property is not established?
  1. That the method finishes.
  2. That the method stores data.
  3. That the method uses selection.
  4. That the method has an input.
Show answerHide answer
Answer: A
An algorithm must finish after a finite number of steps for its valid inputs. The instruction gives no way to know when repetition ends. Repetition itself is allowed, and a loop can be finite; the missing stopping rule is what prevents a termination argument here.

Question 10 of 10

What values remain after this pseudocode?

a ← 6
b ← 11
a ← b
b ← a
  1. a = 11, b = 6
  2. a = 11, b = 11
  3. a = 6, b = 11
  4. a = 6, b = 6
Show answerHide answer
Answer: B
The third line copies 11 into 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
  1. "Medium" only.
  2. "High" only.
  3. "High", then "Medium".
  4. "Low" only.
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
  1. 4 times.
  2. 6 times.
  3. 5 times.
  4. 2 times.
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
  1. 3, 1, −1.
  2. 5, 3, 1.
  3. 3, 1.
  4. 5, 3, 1, −1.
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

An outer loop visits rows 1 through 3. For each row, an inner loop visits columns 1 through 5 and adds 2 to a total initialized once to zero. What total remains?
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A sensor value must be from 4 inclusive to 9 exclusive. What condition checks this?
  1. value ≥ 4 OR value < 9
  2. value ≥ 4 AND value < 9
  3. value > 4 AND value ≤ 9
  4. value ≤ 4 OR value ≥ 9
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A duration is 248 minutes. What values do 248 DIV 60 and 248 MOD 60 give, in that order?
  1. 4 and 8.
  2. 4 and 48.
  3. 8 and 4.
  4. 3 and 68.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A measurement is accepted when it is at least 12. What comparison should test acceptance?
  1. measurement > 12
  2. measurement ≤ 12
  3. measurement = 12
  4. measurement ≥ 12
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

A nonempty list may contain any integers. A largest-value method initializes largest ← 0 and replaces it only when a larger item appears. What single change makes its starting value valid for every such list?
  1. Replace the comparison > with ≥.
  2. Initialize largest to the last item plus 1.
  3. Reset largest to zero before every comparison.
  4. Initialize largest to the first list item.
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

A program runs without a crash but rejects a qualifying score because it uses > where the rule needs ≥. What kind of error is this?
  1. A syntax error.
  2. A logic error.
  3. A runtime error.
  4. An input typing error.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What flowchart symbol should contain distance ← speed * time?
  1. An input/output parallelogram.
  2. A decision diamond.
  3. A Start/End terminator.
  4. A process rectangle.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A flowchart inputs a whole-number count and reaches a diamond labeled count = 0?. For count 3, where should execution go next?
  1. Along the exit labeled Yes.
  2. Along the exit labeled No.
  3. Along both exits in sequence.
  4. Back to Start before choosing.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A flowchart tests items > 0? before a repeated body. Yes enters the body and returns to the test; No goes to End. What pseudocode structure matches it?
  1. WHILE items > 0 DO … END WHILE
  2. REPEAT … UNTIL items > 0
  3. IF items > 0 THEN … END IF
  4. FOR items ← 0 TO 1 … END FOR
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A program accepts whole-number ages from 18 through 65 inclusive. What input directly checks whether its upper endpoint is wrongly excluded?
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A mean program divides total by count. It works for several nonempty lists but fails on an empty list. What should be handled before the division?
  1. The case where count is zero.
  2. The case of a negative total.
  3. The first value below the last.
  4. Repeated values in the list.
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
  1. 1, 2, 4.
  2. 2, 3, 4.
  3. 2, 4, 8.
  4. 2, 4, 6.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A login flow reads a code, increases attempts, and loops back if the code is wrong AND attempts < 4. On the fourth attempt the code is correct. After the loop, what test should choose between "Accepted" and "Limit reached"?
  1. Whether attempts is less than four.
  2. Whether the entered code is correct.
  3. Whether the loop body ran at least once.
  4. Whether attempts equals its starting value.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program must accept integer temperatures from −8 through 12 inclusive. It currently checks 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?
  1. −7, accepted.
  2. 11, accepted.
  3. −9, rejected.
  4. −8, accepted.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A flowchart initializes 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?
  1. To the input step after initialization.
  2. To the initialization step before input.
  3. To the output step after the decision.
  4. To the addition step without reading input.
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

A Scratch stack runs when clicked in the workspace but does nothing when the green flag is clicked. What should start the stack for that event?
  1. A "when green flag clicked" hat.
  2. A "when this sprite clicked" hat.
  3. A "stop all" cap at the bottom.
  4. A rounded reporter at the top.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What kind of Scratch block supplies TRUE or FALSE to an if condition slot?
  1. A rounded text reporter.
  2. A stack command block.
  3. A six-sided Boolean block.
  4. A starting event hat.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

In Scratch, 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

In Scratch, done is already TRUE before a "repeat until " block. How many times does its body run?
  1. One time.
  2. Two times.
  3. It repeats until stopped.
  4. Zero times.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A Scratch script asks for a city and then evaluates "join [City: ] (answer)". What extra action displays the resulting text in the sprite’s speech bubble?
  1. Put a set-variable block after the join.
  2. Put the join reporter inside a say block.
  3. Put the join inside another join reporter.
  4. Put a comparison block around the join.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What is the input parameter in a custom block named "draw path (length)"?
  1. The named value length.
  2. The stack that calls it.
  3. The green flag event.
  4. The sprite’s costume.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A controller broadcasts "prepare". A receiver spends two seconds moving a sprite to its starting position. The controller must announce "Ready" only after that receiver finishes. What change establishes the required order?
  1. Put the receiver below the controller in the workspace.
  2. Use "broadcast prepare and wait" before saying "Ready".
  3. Broadcast "prepare" immediately after saying "Ready".
  4. Use two ordinary broadcasts before saying "Ready".
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two green-flag scripts both set the same variable to different values, then finish. A third script reads it without coordination. Why is relying on one chosen final value unsafe?
  1. The variable keeps both assigned numbers as a two-item list.
  2. The lower script in the workspace must always assign its value last.
  3. The scripts run concurrently, so write timing can change the value read.
  4. The assignment with the larger number must always replace the smaller.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A guessing game asks once, then repeats until answer = secret. Inside it, the sprite gives high/low feedback but never asks again. The first guess is wrong. What prevents the loop from ending?
  1. The loop checks its stopping condition before its first body pass.
  2. The feedback chooses between a high message and a low message.
  3. The secret was chosen before the initial question was displayed.
  4. No instruction obtains a new answer for the next condition check.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A custom block draws a regular polygon using inputs for side count and side length. What gives it generalization?
  1. Its name lets the caller ignore the internal drawing steps.
  2. Its hat block starts when the green flag event happens.
  3. Its changing inputs let one method handle different cases.
  4. Its category makes all block combinations logically correct.
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
  1. 14, 9.
  2. 15, 9.
  3. 15, 15.
  4. 9, 14.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A museum model stores visitor counts by room. A new task must plan wheelchair-accessible routes. What is the main reason the model needs more information?
  1. Every model must include every physical feature of a building.
  2. The new purpose needs access details the count model omitted.
  3. The model needs more visitor samples before route planning can work.
  4. The model can serve the new task if counts are stored more precisely.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A method repeatedly halves a sorted set of 64 possible pages. The set then grows to 256 pages. How does the number of halvings needed to reduce it to one page change?
  1. It rises from 6 to 24.
  2. It rises from 8 to 10.
  3. It rises from 6 to 8.
  4. It rises from 32 to 128.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A system accepts a sample only if its mass is from 2 to 5 kg inclusive and its label is readable. The current test is (mass ≥ 2 AND mass ≤ 5) OR readable. What erroneous acceptance can occur?
  1. A 6 kg sample is accepted when its label is readable.
  2. A 3 kg sample is rejected when its label is readable.
  3. A 2 kg sample is rejected when its label is readable.
  4. A 5 kg sample is rejected when its label is readable.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A program tries to divide by zero while processing data and stops with an error. What kind of failure has occurred?
  1. A syntax error.
  2. A logic-only misclassification.
  3. A decomposition overlap.
  4. A runtime error.
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
  1. 2.4.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A controller uses "broadcast and wait" to finish setup before play starts. One setup receiver contains a "forever" loop. No stop action occurs. What happens to the controller’s next block?
  1. It runs as soon as the receiver begins its first pass.
  2. It keeps waiting because that receiver never finishes.
  3. It runs after exactly one pass of the receiver loop.
  4. It runs when all receiving scripts have started together.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team designs an entry recorder that adds one to attendance, a welcome-message module that also adds one for that arrival, and a display module. What responsibility should change to avoid a wrong total?
  1. Only one module should increment attendance for each arrival.
  2. Both modules should wait for display before incrementing attendance.
  3. The display module should reset attendance before either increment.
  4. The two increments should run together after the welcome message.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An algorithm starts 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?
  1. Initialize n to 2: the post-test version outputs 6, the pre-test version 6.
  2. Initialize n to 4: the post-test version outputs 6, the pre-test version 6.
  3. Initialize n to 6: the post-test version outputs 8, the pre-test version 6.
  4. Initialize n to −2: the post-test version outputs 6, the pre-test version 6.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A team asks whether a precisely stated problem has any algorithmic solution, before anyone writes a program. What part of computer science does this illustrate?
  1. Studying the limits of computation.
  2. Choosing hardware for an organization.
  3. Drawing conclusions from a sample of data.
  4. Writing executable language syntax.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

90 Key Terms, each with its definition

A

Abstraction
Abstraction is keeping the details a particular purpose needs while hiding other details, so a problem or component is easier to use.
A metro map can preserve connections while leaving out the street layout between the stations.
Abstraction layer
An abstraction layer is a level of a system that provides defined behavior while hiding the details of how lower-level work is performed.
A chat app relies on operating-system services without making its user control hardware directly.
Accumulator
An accumulator is a variable that builds a running result over loop passes, incorporating each new contribution into the stored value.
A running total adds the next temperature to the amount already accumulated from earlier days.
Algorithm
An algorithm is a finite, ordered collection of precise instructions that produces the required output for every input within its valid domain.
A correct largest-value method must inspect enough of the list to handle a maximum in the middle.
Answer reporter
The answer reporter is a Scratch value block providing the latest response entered through an ask-and-wait block for later processing.
After asking for a name, a script can place answer inside join to build a personal greeting.
Assignment
Assignment is storing a newly evaluated value in a variable, replacing the value that was previously stored under that name.
In count ← count + 1, the old count is read before the new value is placed back into count.

B

Block-based programming
Block-based programming is building a program from graphical instruction and value blocks whose shapes guide how they can be combined.
A beginner can assemble a loop without typing the punctuation required by a text-based language.
Boolean
A Boolean is a data value with one of two possible states, TRUE or FALSE, commonly produced by a comparison or logical operation.
The comparison score ≥ 50 supplies a Boolean that decides which branch of the algorithm runs.
Boolean block
A Boolean block is a six-sided Scratch value block that supplies TRUE or FALSE for the condition slot of a decision or loop.
A sensing comparison can tell an if block whether its sprite is touching the mouse pointer.
Boundary test
A boundary test checks a valid endpoint or decision threshold and nearby values, where small comparison errors can change acceptance.
Testing exactly 50 exposes a strict greater-than comparison when a pass rule includes that score.
Branch
A branch is one possible path through a decision, containing the work executed when its labeled condition or case is selected.
In a login flowchart, the successful-login branch displays "Welcome" and then rejoins the flow before End.
Broadcast
A broadcast is a Scratch message sent to all sprites and the stage, starting any scripts whose receiving hats match that message.
A controller can send "prepare" so that several sprites move into position through their own receivers.

C

Computation
A computation is a process that carries out instructions on input information to produce a result, which may then be used by another process.
A route computation takes locations and map data and produces a route with a distance and travel time.
Computational thinking
Computational thinking is a way to formulate problems and solutions as steps that a person, computer, or combination of both can carry out.
Planning shared ingredients for several meals uses computational thinking before any software is involved.
Computer engineering
Computer engineering is the design and development of physical computing hardware, such as processors, circuit boards, and related devices.
Designing a processor circuit emphasizes computer engineering, while studying solvable problems emphasizes theory.
Computer science
Computer science is the study of computation, information, and the design of systems that solve problems through precise processes.
A computer scientist can study whether a problem is solvable before anyone writes an executable program.
Concurrency
Concurrency is the execution of several scripts over overlapping time periods, so their actions may depend on timing unless coordinated.
Two scripts writing different values to one variable need a plan before another script relies on its value.
Condition
A condition is an expression evaluated as TRUE or FALSE, supplying the decision used by a branch or condition-controlled loop.
The condition remaining > 0 decides whether another item should be processed by the loop.
Condition-controlled loop
A condition-controlled loop decides repetition using a Boolean test, so the number of passes can depend on changing data or new input.
A guessing game can continue asking until the answer matches the secret value chosen at the start.
Connector
A connector is a labeled flowchart symbol that links separated portions of execution flow, helping the reader follow a continuation across the diagram.
Matching connector labels can replace a long crossing line that would make a large chart hard to follow.
Constant
A constant is a named value that remains unchanged throughout an algorithm, making a fixed rule or quantity explicit in its instructions.
A named pass threshold can be compared with many scores without changing during the computation.
Constraint
A constraint is a rule or limit that a solution must respect, shaping which possible results or methods are acceptable.
A meal plan has to respect the available cooking time as well as each person’s dietary needs.
Control structure
A control structure is a way to organize execution order, including sequential steps, conditional choices, and repeated blocks of work.
A list-processing algorithm can put a decision inside a loop and update a variable in sequence.
Correctness
Correctness is the property of producing the required behavior for every valid input while respecting the problem’s specified rules.
A method that finds the maximum only when it is at a list endpoint is not correct for all lists.
Count-controlled loop
A count-controlled loop repeats its body a known number of times, often using a counter whose values cover a specified inclusive range.
A FOR loop from 1 through 5 runs five passes, while starting at 0 adds one more pass.
Counter
A counter is a variable used to record how many times an event occurs or how many items have been processed during execution.
The count increases once per reading so that the final total can be divided by the number of readings.
Custom block
A custom block is a named Scratch procedure whose definition contains reusable commands and can include input parameters for changing values.
A square block can draw sides of different lengths when each call supplies a new size.

D

Data science
Data science is using statistics and computing to draw conclusions from data, combining quantitative reasoning with methods for processing information.
A data scientist can study recorded measurements to identify trends and evaluate possible explanations.
Data type
A data type identifies the kind of value being represented and helps determine which operations are meaningful for that value.
Adding numbers calculates a numeric sum, while joining two strings puts their text together.
Debugging
Debugging is finding and fixing the cause of a program failure by reproducing it, inspecting execution, and checking the effect of a repair.
The first unexpected trace value can point to an update that erased the accumulated result.
Decision symbol
A decision symbol is a flowchart diamond that tests a condition or value and chooses exactly one of its labeled outgoing paths.
The diamond score ≥ 50? sends a qualifying score along Yes and a lower score along No.
Decomposition
Decomposition is breaking a complex task into smaller subproblems that can be understood, solved, and checked before being combined.
A quiz can separate presenting a question from checking the response and updating the score.
Decomposition diagram
A decomposition diagram is a tree showing how a whole task is divided into smaller responsibilities at successive levels of detail.
Branches beneath “Ask a question” can show displaying text, displaying choices, and reading input.
Dependency
A dependency is a relationship in which one task needs another task’s result, restricting when the dependent task can proceed.
In a quiz, the scoring task must receive the checked answer before it can decide whether to add a point.
DIV
DIV is an integer-division operator that gives the whole-number quotient, counting complete groups of the divisor in a nonnegative dividend.
For 135 minutes, 135 DIV 60 identifies two complete hours before the remaining minutes are handled.
Dry run
A dry run is manually following an algorithm with chosen input values, recording its actual operations without executing a computer program.
A learner uses a trace table to desk-check a loop’s first pass, last pass, and stopping test.

E

ELSE IF chain
An ELSE IF chain tests conditions in order and executes only the first matching branch, with an optional final ELSE for unmatched cases.
Overlapping “at least” thresholds need careful ordering so an early branch does not catch every case.
Event
An event is an occurrence, such as a key press or message receipt, that can trigger scripts registered to respond to it in a program.
Clicking the green flag starts the Scratch scripts that have matching green-flag hats.
Event handler
An event handler is a script or piece of code that starts when a particular event occurs and performs the response assigned to that event.
A “when I receive [game over]” script can stop movement when the project sends that message.

F

Flow line
A flow line is an arrowed connection between flowchart symbols that specifies which step follows another, including a return to repeated work.
A backward flow line can return from the body’s update to the decision that controls another pass.
Flowchart
A flowchart is a diagram that represents algorithm steps with symbols and shows execution order through directed connecting flow lines.
Following a single set of input values through the arrows reveals the path that run will take.
Forever block
A forever block is a Scratch loop that keeps executing its body until the script or program is stopped, supporting ongoing behavior.
A game can use a forever loop to keep checking whether a key is being pressed.

G

Generalization
Generalization is turning a particular solution into a method for a family of cases by identifying what stays fixed and what can vary.
One polygon-drawing method can accept different side counts instead of having one script for each shape.

H

Hat block
A hat block is a Scratch script starter whose shape sits above the command stack and identifies the event that triggers its attached instructions.
A green-flag hat makes its stack respond to the flag, while a key-press hat responds to that key.

I

Infinite loop
An infinite loop is repetition that never ends because execution never reaches a state or action that stops the repeated work.
A positive countdown repeats forever if its body never decreases the value tested by the loop.
Information technology
Information technology is the work of selecting, setting up, maintaining, and operating computing systems for an organization.
An IT team can configure the computers and accounts that an organization needs for its daily work.
Input
An input is data supplied to a computation before or during its execution, providing information that its instructions can use.
A temperature entered by a user is input to a program that decides which message to display.
Input/output symbol
An input/output symbol is a flowchart parallelogram representing a step that receives data or sends a result to a user or another destination.
Reading a room length and displaying an area both use data symbols, while the calculation uses a rectangle.
Integer
An integer is a whole number that can be negative, zero, or positive, making it suitable for counts and other values without a fractional part.
A loop counter takes integer values, while the calculated mean of its input values may be fractional.
Iteration
Iteration is repeating a block of instructions under a count or condition, allowing a method to handle repeated work without duplicating its steps.
A loop can apply the same comparison to every candidate while keeping the best value seen so far.

J

Join block
The join block is a Scratch reporter that builds one text value by combining two supplied pieces of text without displaying them itself.
A say block can display the greeting constructed by joining "Hello, " with the answer reporter.

L

List
A list is an ordered collection of values treated as one data item, allowing an algorithm to visit its elements and combine or compare them.
A FOR EACH loop can visit the temperature readings in a list and accumulate their total.
Logic error
A logic error is a flaw in the instructions that makes a running program produce behavior or results that differ from the required rules.
Using a strict comparison for an inclusive pass threshold wrongly rejects the score at the threshold.
Logical operator
A logical operator combines or reverses Boolean conditions: AND requires both, OR requires at least one, and NOT reverses a value.
A valid-interval check combines its lower and upper limits with AND so that both must hold.

M

MOD
MOD is an integer operator that gives the remainder after whole-number division; for nonnegative inputs it is what remains after complete groups.
The value 135 MOD 60 gives the 15 minutes left after two complete hours have been removed.
Model
A model is a simplified representation of something that preserves enough relevant information to answer questions for a particular purpose.
A parking model records a car’s identity and arrival time without simulating how its engine works.

N

Nesting
Nesting is placing a control structure inside another structure’s body, so reaching the inner structure depends on the surrounding flow.
An inner password check can run only after the outer length check has sent execution into its branch.

O

Off-by-one error
An off-by-one error is a boundary mistake that makes a count or repeated process include one item too many or one item too few.
A countdown using n ≥ 0 outputs zero as well as the positive values if that body outputs n.
Output
An output is a result sent out by a computation, such as displayed text, a calculated value, or data passed to another process.
The mean mass shown after processing a collection of measurements is the calculation’s output.

P

Parameter
A parameter is a named input in a procedure’s definition that lets its instructions work with values supplied by different calls.
The size parameter lets a drawing procedure use 60 steps on one call and 100 on another.
Pattern recognition
Pattern recognition is identifying similarities, repetitions, or trends within data or tasks that suggest a shared structure or reusable method.
Repeated move-and-turn pairs suggest a loop when a pen follows the sides of a regular polygon.
Post-test loop
A post-test loop evaluates its controlling condition after the repeated body, so the body executes at least once before a stopping decision.
A REPEAT … UNTIL login asks for a password before deciding whether another attempt is needed.
Pre-test loop
A pre-test loop evaluates its controlling condition before entering each body execution, allowing the body to run zero times when entry fails.
A WHILE chart can go straight from its first decision to the step after the loop.
Predefined process
A predefined process is a flowchart step calling a procedure described separately, drawn as a rectangle with double vertical lines at its sides.
A main chart can call a checking procedure without drawing every internal comparison on the same page.
Problem-solving cycle
A problem-solving cycle is a process of understanding, planning, carrying out, and checking a solution, with revisions when needed.
A failed test can send a designer back to change the original plan or include a missing input.
Procedure
A procedure is a named group of instructions that can be called to perform a job, sometimes with supplied inputs or a returned result.
A caller can use an average procedure without rewriting its addition and division steps each time.
Process symbol
A process symbol is a flowchart rectangle representing an action or calculation that changes or works with the program’s current data.
The rectangle area ← length * width calculates a value after the two measurements have been read.
Program
A program is a set of instructions expressed in a programming language so that a computer can carry out the specified behavior.
A flowchart and a runnable program can express the same method through different representations.
Programming
Programming is writing instructions in a language a computer can execute, turning a planned method into runnable behavior.
A developer can implement the same calculation method in several different programming languages.
Pseudocode
Pseudocode is a structured, readable description of an algorithm that expresses its logic without following one programming language’s syntax.
Capital keywords and indented blocks make the intended loop structure visible before implementation.

R

Real-valued data
Real-valued data represents numerical quantities that may have fractional parts, commonly stored with a floating-point data type in a program.
A measured room length of 4.5 meters needs a numeric type that can represent its fractional part.
Repeat block
A repeat block is a Scratch control block that runs its enclosed commands a specified number of times before continuing with the next block.
Repeating a move-and-turn pair four times can draw a square when the pen is down.
Repeat-until block
A repeat-until block is a Scratch loop that checks a Boolean before each pass and repeats its body while that stopping condition is FALSE.
If the first guess is correct, a repeat-until-correct block skips its feedback body entirely.
Reporter block
A reporter block is a rounded Scratch block that supplies a value, such as text or a number, to an input slot in another block.
The score reporter supplies the current number to a comparison that checks whether the target was reached.
Return value
A return value is a result a procedure sends back to its caller, where it can be stored, combined with other data, or passed onward.
An average procedure can return 20 so that the caller can compare it with another measurement.
Runtime error
A runtime error is a failure encountered while a program executes, often triggered by a particular input or state during an operation.
An empty-list mean reaches division by zero if its count is used without an earlier check.

S

Script
A script is a connected stack of Scratch blocks that describes ordered behavior, commonly started by an event hat when its event occurs.
A green-flag script can reset a variable, ask a question, and then choose a feedback message.
Selection
Selection is the control structure that tests a condition and chooses which branch of instructions should execute for the current state.
A pass check chooses one message when the score qualifies and another when it does not.
Sequence
Sequence is the control structure in which instructions execute one after another, with each later instruction using the state left earlier.
Reading a measurement before calculating its result is a sequence with a necessary dependency.
Sprite
A sprite is a character or object in a Scratch project with its own scripts, costumes, and sounds that can respond to events and perform actions.
Two sprites can respond to the same broadcast while carrying out different jobs in the project.
Stage
The stage is Scratch’s visible project area, measuring 480 by 360 units, with horizontal and vertical coordinates centered on (0, 0).
A sprite sent to x: 0 and y: 0 moves to the center before carrying out the next block.
String
A string is a sequence of text characters, allowing a program to store names, messages, or numeric-looking text as textual data.
Joining the strings "12" and "3" produces "123", which differs from calculating their numeric sum.
Subproblem
A subproblem is a smaller task within a larger problem, with a responsibility that contributes to solving the whole problem.
Displaying answer choices is a subproblem within the larger task of asking a quiz question.
Success criterion
A success criterion is a specific way to judge whether a solution has achieved its intended result and met the problem’s needs.
A shopping list succeeds when it supplies enough of every ingredient required for the chosen meals.
Syntax error
A syntax error is a violation of a programming language’s writing rules that prevents the affected instructions from being interpreted correctly.
A missing closing parenthesis can stop text code from running before its logic is tested.

T

Terminator
A terminator is a flowchart symbol, drawn as an oval or rounded rectangle, that marks a starting or ending point in execution.
A room-area chart begins at Start and reaches End after the calculated area has been displayed.
Top-down decomposition
Top-down decomposition is refining a whole problem into main parts and then refining those parts into smaller, more directly solvable tasks.
A designer identifies quiz responsibilities before deciding the detailed actions within each screen.
Trace table
A trace table is a record of variable values, condition results, and outputs as an algorithm’s instructions are followed in a particular run.
A running-sum trace shows the total after each addition, making an unexpected reset visible.
Trend
A trend is a recurring direction or relationship observed across data, which can guide predictions when the pattern remains relevant.
A shop compares umbrella sales with rain forecasts before using that pattern to plan its stock.

V

Variable
A variable is a named storage location whose current value can be read and replaced while an algorithm or program executes.
A counter variable changes from 4 to 5 after an instruction adds one to its current value.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started