MGU Computer Science Series — CS Foundations
Part I: What Computer Science Studies
Decomposition · Patterns · Abstraction · Algorithms · Testing
Chapter 3 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition
Part I — What Computer Science Studies

Chapter 3:
Problem Solving and
Computational Thinking

Decomposition, pattern recognition, abstraction, algorithmic thinking, modeling, testing, and the habits of mind that computer scientists use before writing a single line of code

■ CS Level: Foundations ■
■ 9 Sections  •  Part I of 7 ■
■ No Prior Programming Required ■

"The computer is incredibly fast, accurate, and stupid. Human beings are incredibly slow, inaccurate, and brilliant. Together they are powerful beyond imagination."

— attributed to Albert Einstein

Follows Chapter 2: Computers, Information, and Computation  ·  Prepares students for Chapter 4: Data, Representation, and Binary

Purpose and Overview

Every field of study has habits of thought — ways of approaching problems that experts use so naturally they barely notice them. Mathematicians look for structure and proof. Scientists look for patterns and test hypotheses. Engineers think about tradeoffs and constraints. Computer scientists have their own set of habits, and those habits have a name: computational thinking.

This chapter teaches you how computer scientists think before they write a single line of code. You will learn to break large problems into smaller pieces, recognize patterns in data and situations, use abstraction to focus on what matters, design precise procedures, build models, test solutions, and refine your work when the first approach fails.

These habits are not just useful for programming. They apply any time you face a problem with many moving parts, involves information, or requires a repeatable procedure. After this chapter, you will find yourself recognizing computational thinking in recipes, in games, in scientific experiments, and in the systems that quietly run the world around you.

Opening Question

A hospital wants to build a system to schedule patient appointments. Before anyone opens a code editor, the team must figure out what information the system needs, what rules govern scheduling, what happens when a doctor cancels, and how nurses, doctors, and patients each interact differently. None of these questions are answered by code. They are answered by careful, structured thinking about the problem itself. That thinking is what this chapter teaches.

9Sections
4Core Ideas
20+Key Terms
15+Exercises

Learning Objectives

  1. 1Explain what computational thinking means and why it matters before writing code.
  2. 2Apply decomposition to break a large problem into smaller, manageable sub-problems.
  3. 3Recognize patterns in data and in the structure of computing problems.
  4. 4Apply abstraction to identify what details matter and what can be safely left out.
  5. 5Define the three essential properties of a correct algorithm.
  6. 6Trace an algorithm step by step with a given input and record each variable's value.
  7. 7Write a simple procedure using pseudocode and represent a decision using a flowchart.
  8. 8Describe the purpose of a model and explain the tradeoff between accuracy and simplicity.
  9. 9Design a test plan that includes typical cases, boundary cases, and edge cases.
  10. 10Explain what debugging and iteration mean in problem solving.
  11. 11Identify computational thinking habits in everyday situations outside of programming.

Sections at a Glance

Sections 3.1 – 3.2
The Framework and Its First Pillar
What Computational Thinking Means · Decomposition

What Computational Thinking Means

A common misconception about computer science is that it begins with typing code. In reality, most of the important thinking in computer science happens before any code is written. Before a single function is defined, professional engineers decide what information their system must track, what rules govern its behavior, what failure modes need to be handled, and how different users will interact with it in different ways. That process of structured problem analysis is what we call computational thinking.

Computational thinking was organized and named as a formal concept by computer scientist Jeannette Wing in an influential 2006 essay. Wing described it as a set of problem-solving habits — not a set of programming skills — that are broadly useful across science, engineering, medicine, business, and daily life.

The Four Core Ideas

Pillar 01
Decomposition
Breaking a complex problem into smaller, more manageable sub-problems that can each be solved independently.
Pillar 02
Pattern Recognition
Noticing similarities, regularities, and recurring structures in data and problems to reuse existing knowledge.
Pillar 03
Abstraction
Focusing on essential information while deliberately leaving out irrelevant detail — the skill of choosing what to ignore.
Pillar 04
Algorithmic Thinking
Designing a clear, precise, step-by-step procedure that solves the problem and can be followed consistently.

These four ideas work together. You decompose a problem into parts, recognize patterns across those parts, abstract away distracting detail, and then design an algorithm for each part. In practice, you move back and forth between these ideas rather than following them in strict order.

Critically, computational thinking is not only for computers. Generals planning campaigns, merchants managing supply chains, and scientists designing experiments were all using forms of computational thinking long before any computing machine existed. What makes computational thinking especially powerful today is that we have computers to execute our carefully designed procedures — millions of times, on millions of data points, without fatigue. The quality of the thinking you do before writing code determines how well the computer can do its job.

Decomposition

Decomposition is the skill of taking a large, complicated problem and breaking it into smaller pieces that are each easier to understand, work on, and solve. The core insight is simple but powerful: a problem that seems impossible all at once may become entirely manageable when divided into parts that can be handled one at a time and then assembled.

Everyday Example
Planning a birthday party for 40 people
  • The taskPlan a birthday party for forty people. Attempting to think about all of it at once — food, invitations, decorations, activities, venue, timing, budget — feels overwhelming.
  • DecomposeGuest list and invitations · Venue selection and booking · Food and drinks · Decorations · Activities and entertainment · Budget tracking
  • ResultEach sub-task can now be worked on independently. Different people can handle different parts. Progress on food does not require the decorations to be finished first. Adjusting one part does not force a redesign of everything else.

Decomposition in Computing

In computing, decomposition happens at multiple levels simultaneously. At the problem level, you decompose a large task into functional areas: a messaging app might split into user accounts, sending messages, storing history, notifications, and settings. At the program level, you decompose a program into functions or modules, each handling one specific task. At the data level, you decompose complex information into records and fields.

Decomposition Diagram — Grade Calculation System
PROBLEM: Calculate each student's final grade for the semester DECOMPOSE INTO: ├── Collect test scores for each student ├── Collect homework scores for each student ├── Collect project scores for each student ├── Apply weights (tests 50% · homework 30% · projects 20%) ├── Compute weighted average for each student └── Assign letter grade based on weighted average
Why Decomposition Matters
  • Manageability. Small problems are easier to reason about. You can give each sub-problem your full attention.
  • Collaboration. Different people or teams can work on different sub-problems simultaneously — only possible with clear decomposition.
  • Reuse. A sub-problem you solve once (temperature conversion, for example) can often be reused in many future programs.
Common Mistake — Wrong Level of Granularity

Decomposing too broadly leaves sub-problems that are still unmanageable ("Step 1: Build the entire user interface"). Decomposing too finely produces so many tiny steps they become hard to track. Good decomposition finds the middle ground: each sub-problem should be small enough to work on independently but large enough to represent a meaningful piece of the whole.

Practice 3.2Decomposition
  1. Decompose the following task into at least five sub-tasks, written as an indented list: Plan and run a one-week summer computer science camp for 30 middle school students.
  2. A ride-share app must match a passenger's request with an available driver. Decompose this matching problem. What information does each party provide? What conditions must be satisfied? What must the system do at each stage?
  3. The following decomposition has a structural problem. Identify it and explain how to fix it.

    TASK: Build a social media posting feature
    ├── Build the entire user interface
    ├── Write all the backend code
    └── Launch the feature
  4. Choose a sport you know well. Identify at least four sub-problems that a computer system tracking scores, statistics, and standings for that sport would need to handle. What data does each sub-problem use? What output does each produce?
Sections 3.3 – 3.4
Seeing What Repeats and What to Leave Out
Pattern Recognition · Abstraction

Pattern Recognition

Pattern recognition is the skill of noticing regularities, similarities, and recurring structures in problems and data. When you recognize a pattern, you gain two advantages. First, you understand the situation better — patterns often reveal underlying structure that is not obvious at first glance. Second, you can reuse what you already know. If a new problem matches a pattern you have seen before, you can adapt an existing solution instead of building from scratch.

Patterns in Data

Consider the sequence 2, 4, 6, 8, 10. Recognizing the pattern (each number is two more than the previous one) lets you predict the next value, write a formula for any term, and design an efficient algorithm that does not need to store every value. Recognizing patterns in data tells you how data is organized, how it grows, and how it can be processed efficiently.

Patterns in Problems

Beyond data, patterns appear in the structure of problems themselves. A program that searches a list for an item, a program that finds the highest-rated restaurant in a dataset, and a program that identifies the student with the most absences all share the same underlying structure: find the element in a collection that best satisfies a condition. Once you recognize this, you can build one general-purpose solution and reuse it in all three situations.

Pattern NameWhat It DescribesExample
CountingCount how many items satisfy a conditionHow many students scored above 90?
AccumulationAdd up values across a collectionTotal sales for the month
FilteringKeep only items that satisfy a conditionShow only in-stock products
SortingArrange items in a specified orderAlphabetize a contact list
SearchingFind an item that satisfies a conditionFind the student with lowest score
TransformationConvert every item in a collection to a new valueConvert all temperatures to Fahrenheit
MatchingCompare two items or two collectionsFind customers who placed two orders
Pattern Recognition and Machine Learning

Machine learning — a major area of modern computing — is largely the science of teaching computers to recognize patterns in data automatically. When a spam filter learns to identify junk email, or when an image classifier learns to recognize faces in photographs, the underlying process is pattern recognition at a massive scale. You will study this in Chapter 26. For now, recognize that this everyday habit of noticing what repeats is one of the most fundamental ideas in all of computing.

Practice 3.3Pattern Recognition
  1. Identify the pattern in each sequence and predict the next two values.
    a. 3, 6, 9, 12, 15, __, __
    b. 1, 2, 4, 8, 16, __, __
    c. 100, 90, 81, 73, 66, __, __ (Hint: differences are decreasing.)
    d. A, B, D, G, K, __, __ (Hint: think about letter positions in the alphabet.)
  2. The three problems below look different on the surface. Identify the single underlying computational pattern they share.

    — Find the student who has the most absences this semester.
    — Find the product with the highest average customer rating.
    — Find the city with the largest population in a dataset.
  3. A programmer has already written a function find_minimum(list) that finds the smallest number in a list. A new problem requires finding the student with the lowest test score from a list of student records. How does pattern recognition help? What would you need to do to adapt the existing solution?
  4. Identify two real-world applications of machine learning you encounter in daily life. For each one, describe: (a) what data the system recognizes patterns in, and (b) what the system does once it recognizes a pattern.

Abstraction

Abstraction is the skill of deliberately leaving out detail in order to focus on what is essential for solving a problem at a given level. Abstraction is everywhere in computing: a programming language is an abstraction of machine code; a function is an abstraction of a sequence of steps; a variable is an abstraction of a memory location. Abstraction is how computer scientists manage complexity — by hiding detail beneath a layer, and working cleanly at the level above.

A Map as Abstraction

A city map does not show every tree, crack in the sidewalk, or window in every building. It shows streets, neighborhoods, landmarks, and distances — the information relevant for navigation. Leaving out detail is not laziness. It is a deliberate choice to include only what serves the purpose. The art of abstraction is knowing which details to leave out and which to preserve, and the answer depends entirely on what problem you are trying to solve. A map for a tourist differs from one for a plumber (showing sewer lines) or an urban planner (showing population density).

Black Boxes in Programming

In programming, abstraction means building tools that hide their complexity and expose only what the user needs to know. A function that computes the area of a circle is a black box: you know what goes in (the radius) and what comes out (the area), but you do not need to know how the multiplication is carried out internally. You simply call circle_area(5) and receive the answer. The implementation details are hidden. This is the essence of abstraction in code.

Levels of Abstraction

One of the most powerful ideas in computer science is that systems are built in layers of abstraction, where each layer hides complexity from the layer above it. You do not need to understand the electrical signals in a keyboard's circuitry in order to type a letter. The programmer building a text editor does not need to understand how the operating system manages keyboard events. Each layer provides a clean interface that the layer above can rely on. This layered structure — called an abstraction hierarchy — is how computers become usable despite their underlying physical complexity.

Levels of Abstraction — Pressing a Key
You press a key on the keyboard ↓ The keyboard hardware detects the keypress (electrical signal) ↓ The operating system registers a keyboard event ↓ The application receives the character code ↓ The screen displays the character Each layer hides the complexity of every layer below it.
Common Mistake — Too Much or Too Little Abstraction

Beginners often write code that is too specific — it solves one exact problem and cannot be adapted without significant rewriting. More experienced programmers can overcorrect and write code so abstract that it becomes difficult to understand and use. Good abstraction is abstract enough to be reusable and clean, yet concrete enough to be understandable and functional.

Practice 3.4Abstraction
  1. A database stores information about books in a library. List five details about a physical book the database should include, and five it can safely leave out. Explain your reasoning for each decision.
  2. The following description is poorly abstracted — it includes too many irrelevant implementation details. Rewrite it as a clean, appropriately abstracted description.

    "The program should accept a text file. The file will be named report.txt and stored in the C:\Users\Documents folder on a Windows 10 computer. It will have between 100 and 500 lines. Each line will end with a carriage return followed by a newline character..."
  3. Describe the layers of abstraction involved when a user in Brazil sends an instant message to a friend in Japan. Identify at least three distinct layers and explain what each one hides from the layer above it.
Sections 3.5 – 3.7
Algorithms, Models, and Step-by-Step Procedures
Algorithmic Thinking · Modeling Problems · Step-by-Step Procedures

Algorithmic Thinking

An algorithm is a precise, finite, step-by-step procedure for solving a problem or accomplishing a task. The word comes from the name of the ninth-century Persian mathematician Muhammad ibn Musa al-Khwarizmi, whose work on arithmetic was enormously influential in medieval Europe. His name, Latinized, became "algoritmi" — and eventually "algorithm."

Three Essential Properties of an Algorithm
  • Precision. Each step must be clear enough that there is no ambiguity about what to do. "Sort the list somehow" is not precise. "Sort the list from smallest to largest" is.
  • Finiteness. The algorithm must eventually stop. A procedure that runs forever is not an algorithm — it is an infinite loop.
  • Correctness. The algorithm must actually solve the problem it is designed to solve. A fast procedure that produces wrong answers is not a correct algorithm.
Algorithms Are Not Programs

An algorithm is a procedure — an idea for how to solve a problem. A program is an implementation of an algorithm in a specific programming language. The same algorithm can be implemented in Python, Java, C, or any other language. In this chapter, all algorithms are written in plain English and pseudocode, not in any programming language. Thinking algorithmically is a skill that exists independently of syntax.

Example Algorithm: Finding the Largest Number

Pseudocode — Find the Largest Number
ALGORITHM: Find the Largest Number

INPUT:  A list of numbers with at least one element

STEP 1: Set current_largest = first number in the list
STEP 2: FOR EACH remaining number in the list:
    STEP 2a:  IF this number > current_largest
                  set current_largest = this number
STEP 3: Report current_largest as the answer

OUTPUT: The largest number in the list

Tracing the Algorithm

Tracing an algorithm means following it step by step with specific inputs, recording every variable's value at every step, to verify the algorithm produces the correct output. Tracing is one of the most important skills in computer science — it is how you check correctness before implementing, and how you find bugs when something goes wrong.

Trace with input list: 7, 3, 12, 5, 9

StepCurrent NumberCurrent LargestAction
Start—7Initialize with first element
1373 is not > 7 — no change
2121212 > 7 — update current_largest
35125 is not > 12 — no change
49129 is not > 12 — no change
End—12Report 12 ✓

Algorithms Have Efficiency

Two algorithms that solve the same problem correctly are not necessarily equal. One may be far faster or use less memory. Consider finding a word in a dictionary: Algorithm A starts at the first page and reads every word until it finds the target (potentially checking all 100,000 words). Algorithm B opens to the middle, discards the half where the word cannot be, and repeats. Algorithm B finds any word in at most 17 steps. Both are correct. But Algorithm B is dramatically more efficient. This distinction — the study of algorithmic efficiency — is one of the central topics of Chapter 12.

Practice 3.5Algorithm Tracing
  1. Trace the Find-the-Largest algorithm with the input list: 15, 8, 23, 4, 19, 11. Show your work in a table with columns for Step, Current Number, Current Largest, and Action.
  2. Trace the following algorithm with name = "AHMED". How many vowels does it count? Show each step.

    STEP 1: Set vowel_count = 0
    STEP 2: FOR EACH letter in name:
       STEP 2a: IF letter is A, E, I, O, or U:
          increase vowel_count by 1
    STEP 3: Report vowel_count
  3. The algorithm below is supposed to sum all numbers from 1 to n. Trace it with n = 5. Identify whether it is correct or contains a bug. (Hint: what is 1+2+3+4+5?)

    STEP 1: Set total = 0, counter = 1
    STEP 2: WHILE counter < n:
       add counter to total
       add 1 to counter
    STEP 3: Report total

Modeling Problems

A model is a simplified representation of something real, designed to help you understand, predict, or reason about that thing. Models are central to science, engineering, economics, and computing. Every model is a simplification — it deliberately leaves out details that are not needed for the purpose at hand. The essential question for any model is: Is this simplification appropriate for the problem I am trying to solve?

In computing, you build a model of a problem before you solve it. You create a mental picture — or a diagram, a data structure, or a table — that captures the important features of the problem and ignores the rest.

Modeling Example
A school library checkout system
  • BOOKTitle · Author · ISBN (unique identifier) · Is it currently checked out? (yes/no)
  • STUDENTStudent ID · Name · List of books currently checked out
  • CHECKOUTStudent ID · Book ISBN · Date checked out · Due date
  • Left outPhysical size of the book · Cover color · Number of pages · Table of contents · Font used in printing. None of these are relevant to the checkout system.

A simulation is a model that runs through time. Instead of representing a system at one instant, a simulation lets you observe how the system changes as time passes and conditions change. Traffic simulations model how cars move through intersections. Weather simulations model how air masses interact. Epidemiological simulations model how diseases spread. Simulations are powerful because they let you test scenarios that would be too costly, dangerous, or slow to test in the real world. You will study simulation in depth in Chapter 13.

Practice 3.6Modeling
  1. Design a data model for a simple school attendance system. Describe what objects the system needs to track, what data fields each object needs, and what the model can safely leave out.
  2. You are designing a simulation of cars approaching a traffic light. What information would your simulation need to track? What simplifications would you make? What would make it more realistic, and is that additional complexity worth it for studying traffic flow?

Step-by-Step Procedures

When you give instructions to a human, they fill in gaps with common sense and ask for clarification when confused. When you give instructions to a computer, the computer does exactly what you say — not what you meant, not what a reasonable person would infer, but precisely and literally what you specified. This fundamental difference demands a level of precision in procedure design that is unusual in everyday life. Every step must be complete. Every condition must be handled. Every exception must be anticipated.

Developing this habit of precise thinking is one of the most valuable things you will gain from studying computer science — and it transfers to many other fields.

Writing Pseudocode

Pseudocode is a human-readable notation that describes an algorithm without following the exact syntax of any programming language. It lets you design a procedure without worrying about syntax errors, so you can focus entirely on whether the logic is correct. There is no single standard for pseudocode — the goal is clarity, not adherence to a particular format.

Pseudocode Example — Assign Letter Grade
PROCEDURE: Assign Letter Grade

INPUT: numeric_score  (a number between 0 and 100)

IF numeric_score >= 90  THEN
    letter_grade = "A"
ELSE IF numeric_score >= 80  THEN
    letter_grade = "B"
ELSE IF numeric_score >= 70  THEN
    letter_grade = "C"
ELSE IF numeric_score >= 60  THEN
    letter_grade = "D"
ELSE
    letter_grade = "F"
END IF

OUTPUT: letter_grade

Flowcharts

A flowchart is a diagram that represents a procedure visually. Flowcharts are especially useful for seeing the decision points and loops in an algorithm — the places where the flow branches or repeats.

SymbolShapeMeaning
Start / EndRounded rectangle (oval)Beginning or end of the procedure
ProcessRectangleA step that performs an action
DecisionDiamondA yes/no question that branches the flow
Input / OutputParallelogramData entering or leaving the procedure
ArrowLine with arrowheadDirection of flow
Flowchart — Assign Letter Grade (simplified)
[START] | ↓ [INPUT: numeric_score] | ↓ Is score >= 90? / \ YES NO | | grade = "A" Is score >= 80? / \ YES NO | | grade = "B" Is score >= 70? / \ YES NO | | grade = "C" Is score >= 60? / \ YES NO | | grade = "D" grade = "F" \ / \ / [OUTPUT: letter_grade] | [END]
Practice 3.7Pseudocode and Flowcharts
  1. Write pseudocode for the following procedure: Given a list of numbers, compute the average (mean). The average is the sum of all numbers divided by the count of numbers. Make sure your pseudocode handles at least one edge case.
  2. Draw a flowchart for a procedure that decides whether a customer is eligible for a discount. The rule is: customers who have spent more than $100 total OR who have placed more than 5 orders receive a 10% discount. Use proper flowchart symbols.
  3. The following pseudocode is meant to print all even numbers from 2 to 20. Find and explain the error, then write the corrected version.

    STEP 1: Set n = 0
    STEP 2: WHILE n <= 20:
       print n
       add 2 to n
Sections 3.8 – 3.9
Testing, Iteration, and the Wider World
Testing and Improving Solutions · Computational Thinking Beyond Programming

Testing and Improving Solutions

One of the most important things to understand about problem solving — in computing and in general — is that the first solution you design is almost never the best one. It may not even be a correct one. This is not a sign of failure. It is a completely normal part of the problem-solving process. Experienced programmers expect to test their solutions, discover problems, fix those problems, test again, and repeat. This cycle is called iteration.

Categories of Test Cases

CategoryDescriptionExample (grade algorithm)
Typical casesThe inputs you most commonly expectScores of 85, 72, 95
Boundary casesInputs exactly at the edge of a conditionScores of exactly 90, 80, 70, 60
Edge casesUnusual or extreme inputsScore of 0, score of 100, score of 101
Invalid inputsInputs that are not what the algorithm expectsA letter instead of a number
Testing Example
Even-or-Odd Algorithm — Test Plan
  • AlgorithmIf n divided by 2 has a remainder of 0, result is "even." Otherwise, result is "odd."
InputCategoryExpected OutputAlgorithm OutputCorrect?
4Typicaleveneven✓
7Typicaloddodd✓
0Edgeeveneven✓
−3Edgeoddodd✓
100Largeeveneven✓

Debugging: Finding and Fixing Mistakes

When a test reveals that a solution produces the wrong output, you must find and correct the mistake. This process is called debugging. (The word "bug" has been used to describe a malfunction since at least the 1940s — there is a famous story about an actual moth found inside the relay of an early computer.) Debugging is a skill that develops with practice. Several strategies help:

Four Debugging Strategies
  • Trace the algorithm. Follow it step by step with the failing input, tracking every variable. Look for where the output first diverges from expectation.
  • Add observation points. Insert print statements at key moments to see the actual values your program is using, not the values you assume it's using.
  • Isolate the problem. Use decomposition to identify which sub-section is producing the wrong result. Narrow the search before examining individual steps.
  • Check your assumptions. Many bugs come from a false belief about how something works. Ask: "What am I assuming here that might not be true?"

Iteration: Improving the Solution

Debugging fixes errors. But even after all known errors are corrected, a solution can often be improved — made faster, clearer, simpler, or better at handling unusual situations. This process of repeated improvement is called iteration. In professional software development, the cycle looks like this:

The Iteration Cycle
1. Design a first version of the solution 2. Test the solution 3. Identify problems, limitations, or areas for improvement 4. Revise the solution 5. Test the revised solution 6. Repeat until the solution meets its requirements
A Principle Worth Remembering

"Make it work, make it right, make it fast." First, get the solution correct. Then improve its clarity and structure. Then, if necessary, optimize its performance. Trying to optimize before you have a correct solution is one of the most common mistakes in software development.

Practice 3.8Testing and Debugging
  1. Design a test plan for an algorithm that takes a positive integer n and returns the sum of all odd numbers from 1 to n. Your plan must include at least one typical case, one boundary case, one edge case, and one invalid-input case. For each test, state the input, expected output, and what aspect of correctness it checks.
  2. A student's grade-assignment algorithm produces "B" for a score of 90 when it should produce "A". Using the trace strategy, identify the most likely location of the bug. What question would you ask when checking assumptions?
  3. Explain the difference between debugging and iteration. Could you have a program that needs iteration but not debugging? Could you have one that needs debugging but not iteration? Give a brief example for each case.
  4. The following algorithm is supposed to count down from 10 to 1 and then print "Done." Identify the bug, explain what will happen when it runs, and write the corrected version.

    STEP 1: Set counter = 10
    STEP 2: WHILE counter > 0:
       print counter
    STEP 3: print "Done"

Computational Thinking Beyond Programming

Computational thinking is not a skill that turns on when you sit at a computer and turns off when you step away. Once you develop these habits, you will find them applying constantly — often without consciously deciding to use them.

In cooking, a recipe is an algorithm. When you adapt a recipe — scaling it for more people, substituting an ingredient — you are debugging and iterating. In travel planning, you decompose the trip (transportation, lodging, activities, budget), recognize pricing patterns, abstract a route map from the noise of a city, and design an algorithm for what needs to happen before departure. In sports coaching, a training plan decomposes a season into phases, recognizes patterns in athlete performance data, abstracts the key variables for a specific athlete, and iterates based on how the athlete responds to load.

In science, computational thinking underlies experimental design: break a hypothesis into testable claims, design controlled experiments that abstract away confounding variables, and iterate based on results. In engineering, it underlies design: decompose a problem into sub-systems, recognize patterns from previous projects, abstract functional requirements from aesthetic details, and prototype and test iteratively.

In artificial intelligence, computational thinking is the deep logic underlying every machine learning system — training data is decomposed into features, patterns are recognized and abstracted into models, and systems are tested and iteratively improved. When you understand computational thinking, you understand the architecture of AI before you learn any of its technical details. Chapter 26 will make that explicit.

Becoming a Computational Thinker

Computational thinking is not a talent you either have or do not have. It is a set of skills that develops with practice. The goal is not to use these ideas as an explicit checklist, but to internalize them so thoroughly that you apply them naturally. As you work through this textbook, you will encounter computational thinking in every chapter, in every problem, and in every program — until it becomes simply the way you see problems.

Practice 3.9Computational Thinking in Everyday Life
  1. Describe a specific real-world problem from your own daily life. Apply all four pillars of computational thinking to it: How would you decompose it? What patterns can you recognize? What abstraction would you apply? What algorithm would you design?
  2. A city wants to design a better system for tracking and filling potholes in its roads. Apply computational thinking to this problem: What data should the system collect? What patterns in that data would be useful? What information can be abstracted away? Design a simple algorithm for prioritizing which potholes to fix first.
  3. Choose any three of the following areas and explain specifically how each pillar of computational thinking applies: sports coaching · emergency medicine · urban planning · journalism · teaching · cooking.

Chapter Summary

Key Terms Review

algorithm
A precise, finite, step-by-step procedure for solving a problem. Must be unambiguous, must eventually terminate, and must produce the correct output.
abstraction
Deliberately leaving out irrelevant details to focus on what matters for solving a problem at a given level. How computer scientists manage complexity.
abstraction hierarchy
A layered structure where each layer hides the complexity of the layers below it and provides a clean interface to the layer above.
black box
A component whose internal workings are hidden. Users interact through its inputs and outputs without needing to understand its implementation.
boundary case
A test input exactly at the edge of a condition, used to verify that limit values are handled correctly.
bug
An error in an algorithm or program that causes it to produce incorrect results or behave in an unintended way.
computational thinking
A set of problem-solving habits — decomposition, pattern recognition, abstraction, and algorithmic thinking — used to formulate and solve problems systematically.
debugging
The process of finding and correcting errors in an algorithm or program by tracing execution, observing values, and checking assumptions.
decomposition
Breaking a complex problem into smaller, independent sub-problems that can each be solved separately and then assembled.
edge case
An unusual, extreme, or boundary-limit input used to reveal failures that typical inputs do not expose.
flowchart
A visual diagram that represents a procedure using standard shapes for processes, decisions, inputs/outputs, and arrows showing direction of flow.
generalization
Moving from a specific instance to a general principle that covers a class of related cases. Closely related to abstraction.
iteration
Repeating a process — design, test, revise — and improving the solution based on the results of each cycle.
model
A simplified representation of a real system designed to support understanding, prediction, or reasoning about that system.
pattern recognition
Identifying regularities, similarities, and recurring structures in data and problems to enable reuse of existing solutions.
pseudocode
A human-readable notation for describing algorithms that resembles code but does not follow the syntax of any specific programming language.
simulation
A model that runs through time, allowing observers to see how a system changes under different conditions without testing the real thing.
test case
A specific input and expected output used to check whether an algorithm or program is producing correct results.
tracing
Following an algorithm step by step with specific inputs, recording each variable's value at each step, to verify correctness.

Concept Check

Answer each question before moving to the practice sections.

  1. What are the four core ideas of computational thinking?
  2. What does it mean to "decompose" a problem? Give one example from daily life.
  3. Give one example of a computational pattern that appears across many different programming problems.
  4. What is the difference between an algorithm and a program?
  5. State the three essential properties of a correct algorithm.
  6. What is a "boundary case" in testing? Why is it important to test boundary cases specifically?
  7. What is iteration, and why is it a normal part of problem solving rather than a sign that something went wrong?
  8. What is abstraction, and why is it useful? What is the risk of applying too much abstraction?
  9. What is a model? In what sense is every model incomplete?
  10. Name two everyday situations — outside of programming — where computational thinking applies.

Debugging and Error Analysis

Each example below contains at least one error. Identify the error and write the corrected version.

Error Analysis 1 — Missing Case
IF number > 0 THEN result = "positive" ELSE result = "negative" OUTPUT: result

What specific input would cause this algorithm to produce an incorrect result? Write the corrected version.

Error Analysis 2 — Operator Precedence
STEP 1: total = a + b + c STEP 2: average = a + b + c / 3 STEP 3: Report average

Identify the error in Step 2. What result would this algorithm produce for inputs a=6, b=6, c=6? What is the correct expression?

Error Analysis 3 — Infinite Loop
STEP 1: Set counter = 10 STEP 2: WHILE counter > 0: STEP 2a: Print counter STEP 3: Print "Done"

What will happen when this algorithm runs? What single line is missing? Write the corrected version.

Error Analysis 4 — Incomplete Test Plan
TEST PLAN for grade assignment algorithm: Test 1: Score = 85, expected "B" Test 2: Score = 72, expected "C" Test 3: Score = 55, expected "F"

Identify at least two important categories of test cases that are missing from this plan. Write two additional test cases that should be included.

Review Questions

  1. Define computational thinking in your own words. Why is it valuable beyond programming?
  2. What is the difference between decomposition and abstraction? Can you practice one without the other? Give an example.
  3. A friend says: "I don't need to learn algorithms — I can just look up how to do things online." How would you respond? What does understanding algorithms give you that copying code does not?
  4. Why does precision matter so much in writing algorithms? Give an example of an instruction that a human would understand correctly but that is ambiguous enough to cause problems for a computer.
  5. What does it mean to test a "boundary case"? Give a specific boundary case for an algorithm that decides whether a student has passed a course (passing = score of 60 or above).
  6. What is the relationship between a model and the real system it represents? What is always true of every model? What does this mean for the limitations of simulations?
  7. Why is iteration a normal and expected part of problem solving rather than evidence of failure?
  8. Explain the following statement: "An algorithm is a recipe for solving a problem; a program is one way of cooking it."
  9. A student writes an algorithm that calculates a restaurant bill including tax. They test it with one input — a $20 meal at 8% tax — and get the correct answer ($21.60). They conclude the algorithm is correct. Is this a sound conclusion? What additional tests should they run and why?
  10. Choose any three areas from this list and explain specifically how all four pillars of computational thinking apply in each: weather forecasting · urban emergency response · athletic training · financial fraud detection · museum curation.

Chapter 3 Checkpoint

Chapter 3 Checkpoint
Complete without assistance — assesses all key skills and concepts from Chapter 3
Section 1 — Vocabulary and Concepts
  1. Name and briefly define each of the four pillars of computational thinking.
  2. Explain the difference between a model and a simulation.
  3. What is pseudocode and why is it used rather than a real programming language when designing algorithms?
Section 2 — Decomposition
  1. A school wants to build a digital system for managing student club memberships. Decompose this problem into at least five sub-problems. For each sub-problem, state what data it works with and what output it produces.
Section 3 — Algorithm Tracing
  1. Trace the following algorithm with the input list: 4, 9, 2, 7, 1. Show your work in a table. What does the algorithm compute?

    STEP 1: Set result = first number in the list
    STEP 2: FOR EACH remaining number n in the list:
       IF n < result THEN set result = n
    STEP 3: Report result
  2. The algorithm above has a conceptual cousin that finds the largest value instead of the smallest. What single word in Step 2a would you change? Why does that one change work?
Section 4 — Pseudocode
  1. Write pseudocode for the following procedure: Given a list of student names and their test scores, print the name and score of every student who scored 90 or above.
  2. Write pseudocode for a procedure that asks a user to enter a positive integer and keeps asking until they enter a valid positive integer. Define what counts as "invalid input."
Section 5 — Testing and Error Analysis
  1. Design a test plan for the student score filter from Question 7. Include at least one test in each of the four test-case categories: typical, boundary, edge, invalid.
  2. The following pseudocode is supposed to compute the sum of all numbers from 1 to n inclusive. Trace it with n = 4 and identify the bug. Write the corrected version.

    SET total = 0, counter = 0
    WHILE counter < n:
       add counter to total
       add 1 to counter
    REPORT total
Section 6 — Application
  1. A hospital emergency room uses a triage system to decide which patients are seen first. Apply all four pillars of computational thinking to this system. Be specific about what information is relevant, what can be abstracted away, what patterns exist in patient data, and what an algorithm for prioritization might look like.

Mixed Review

These questions connect Chapter 3 to earlier chapters.

  1. A smartphone takes a photograph. Using the input-process-output-storage model from Chapter 2, describe what happens. Then identify which step of the computational thinking framework is most relevant to each phase.
  2. From Chapter 1, computer science is described as the study of computation, information, algorithms, programs, machines, systems, networks, data, automation, security, and responsible technology. For each of the following areas, identify the computational thinking skill that is most important for working in it, and explain why: networks · security · automation · data.
  3. In Chapter 2, you learned that computers process information using input, processing, output, and storage. Explain how computational thinking helps you decide what information goes in, what processing should happen, and what information comes out. Give a specific example.
  4. Explain how abstraction relates to the concept of digital representation from Chapter 2. When a computer stores an image as pixels, what details of the real scene has it abstracted away? Why is that abstraction useful and not a problem?
Looking Ahead
Chapter 4: Data, Representation, and Binary

Chapter 4 explores one of the most fundamental questions in computing: how do computers store and process information? Everything in a computer — text, images, sounds, videos, programs, and numbers — is represented using patterns of binary digits called bits. Chapter 4 will teach you how this works, from the basic ideas of bits and bytes, through binary counting and decimal-to-binary conversion, to the representation of text, images, and sound. The chapter is designed to be patient and visual, with many worked examples and practice exercises. The tracing and precision skills you built in this chapter — following a procedure step by step with specific values — will be directly useful when you work through binary conversion algorithms. The habit of asking "what pattern is this?" will help you see the elegant regularity of binary representation rather than just memorizing rules.

MGU Library Connection
  • Pseudocode and Flowchart Reference — Appendix C of this textbook
  • Algorithm Tracing Guide — Companion Resource, MGU CS Series
  • Chapter 5: Algorithms and Instructions — deepens algorithm design with formal pseudocode
  • Chapter 12: Searching, Sorting, and Efficiency — applies these ideas to major algorithm families
  • Chapter 13: Abstraction, Models, and Simulation — extends Section 3.4 and 3.6 to full chapters
  • Chapter 26: Artificial Intelligence and Machine Learning Foundations — applies pattern recognition at scale
  • MGU Glossary entries: algorithm, abstraction, decomposition, pseudocode, flowchart, iteration, debugging