Chapter 5
Computational Thinking, Algorithms, and Problem Solving
Bachelor Program in Mechatronics Engineering
Introduction to Computing
•
Bachelor
Computational Thinking, Algorithms, and Problem Solving
Introduction
Computing is not limited to writing programs. It is a disciplined way of representing problems, reasoning about possible solutions, and constructing procedures that can be executed reliably by people or machines. In mechatronics engineering, this discipline supports sensor-data processing, robotic control, embedded systems, manufacturing automation, simulation, diagnostics, and human–machine interaction.
A mechatronics problem often combines mechanical behavior, electrical signals, control logic, and software. For example, an automated conveyor must detect an object, determine whether it satisfies a dimensional requirement, activate an actuator, and respond safely if a sensor fails. Solving such a problem requires more than selecting programming syntax. The engineer must clarify the problem, identify relevant information, design a procedure, assess efficiency and correctness, and communicate the solution clearly.
This chapter introduces computational thinking and the principal tools used to transform an informal problem into an executable solution: decomposition, abstraction, pattern recognition, algorithms, pseudocode, flowcharts, structured problem solving, correctness reasoning, and complexity analysis.
Learning Objectives
By the end of this chapter, the reader should be able to:
Explain computational thinking and distinguish it from merely programming.
Decompose complex engineering problems into manageable subproblems.
Use abstraction and pattern recognition to construct useful models.
Specify inputs, outputs, assumptions, constraints, and edge cases.
Write unambiguous pseudocode and interpret flowcharts.
Design algorithms using sequence, selection, iteration, and modularity.
Evaluate algorithms using correctness, termination, time complexity, and space complexity.
Apply a structured problem-solving process to a mechatronics application.
Recognize limitations, ethical concerns, and safety implications of computational solutions.
1. Computational Thinking as an Engineering Competence
Computational thinking is a problem-solving approach that expresses a problem in a form suitable for systematic reasoning or computation. It includes four closely related practices:
Decomposition: breaking a large problem into smaller, more understandable tasks.
Abstraction: retaining important features while suppressing unnecessary detail.
Pattern recognition: identifying similarities that permit reuse of methods or models.
Algorithm design: specifying finite, ordered steps that transform inputs into outputs.
These practices are iterative rather than strictly sequential. An engineer may decompose a problem, discover a repeated pattern, revise the abstraction, and then redesign the algorithm.
Programming is the implementation of an algorithm in a particular language. Computational thinking occurs earlier and at a broader level. A poor design written in excellent code remains a poor solution; conversely, a well-designed algorithm can often be implemented in several languages or hardware platforms.
The computational problem statement
Before designing an algorithm, formulate the problem precisely. A useful statement identifies:
Element
Guiding question
Goal
What must be achieved?
Inputs
What data or signals are available?
Outputs
What result, action, or decision is required?
Constraints
What limits time, memory, energy, accuracy, or cost?
Assumptions
What conditions are treated as true?
Edge cases
What unusual or boundary situations may occur?
Success criteria
How will correctness and performance be judged?
For instance, “control the motor” is incomplete. A stronger formulation is: “Given a target speed, measured speed, maximum allowable current, and sampling interval, determine a safe actuator command that reduces speed error without exceeding the current limit.”
2. Decomposition, Abstraction, and Patterns
2.1 Decomposition
Decomposition reduces cognitive complexity. An automated sorting cell might be divided into:
Acquire sensor measurements.
Validate measurements.
Classify the part.
Schedule the appropriate actuator action.
Monitor actuator completion.
Record the result and report faults.
Each task can be specified, tested, and replaced independently. This supports modularity, maintenance, and teamwork. Decomposition should not create arbitrary fragments; each module should have a clear responsibility and a well-defined interface.
A module interface specifies what enters and leaves a module. For example, a classifyPart module might accept calibrated height and mass values and return one of ACCEPT, REJECT, or UNKNOWN. It should not secretly alter unrelated system state.
2.2 Abstraction
Abstraction creates a model at an appropriate level of detail. A motor can be represented as:
a physical electromechanical system involving torque, inertia, friction, and current;
a control-system block with an input command and measured speed; or
a software object with operations such as start(), stop(), and readSpeed().
Each representation is useful for a different question. Abstraction is not the removal of all detail. It is the deliberate selection of detail relevant to the current purpose.
An abstraction may be procedural, describing what an operation does; data-oriented, describing the structure of information; or physical, describing an engineering system through variables and relationships. Incorrect abstraction can omit safety-critical conditions. For example, representing a sensor only as a numerical value may hide the distinction between a genuine zero and a disconnected sensor.
2.3 Pattern recognition
Patterns enable reuse. Common computational patterns include:
accumulating a total;
counting events satisfying a condition;
finding a maximum or minimum;
searching for a value;
filtering invalid measurements;
processing every item in a sequence;
retrying an operation under a bounded policy;
using a state machine for operating modes.
Suppose several machines require “read, validate, transform, and log” behavior. Recognizing this pattern can lead to a reusable data-processing module rather than separate, inconsistent implementations.
3. Algorithms and Their Properties
An algorithm is a finite, ordered, unambiguous procedure for solving a class of problems. A practical algorithm should possess the following properties:
Input: it accepts zero or more well-defined inputs.
Output: it produces at least one result or observable action.
Definiteness: each step is sufficiently precise.
Finiteness: it terminates after a finite number of steps, unless it is intentionally a continuously operating controller.
Effectiveness: each step can be carried out using available operations.
Generality: it solves a class of valid instances rather than one accidental example.
A continuously running embedded controller is not finite in its overall operation, but its individual control cycle should be finite and bounded. This distinction is important in real-time systems.
Algorithm representation
Algorithms may be represented by structured English, pseudocode, flowcharts, state diagrams, decision tables, or executable code. Pseudocode is often preferable during design because it communicates logic without committing to programming-language syntax.
A convention used in this chapter is:
← means assignment;
= in a condition means equality comparison;
indentation indicates block structure;
IF, ELSE, WHILE, and FOR identify control structures;
comments explain intent rather than restating syntax.
Fundamental control structures
Sequence executes instructions in order.
read temperature
convert temperature to degrees Celsius
display temperature
Selection chooses among alternatives.
IF temperature > upperLimit THEN
activate cooling
ELSE
deactivate cooling
END IF
Iteration repeats instructions.
FOR each measurement in sampleSet
add measurement to total
END FOR
A WHILE loop is suitable when the number of repetitions is not known in advance, but it must have a condition that eventually becomes false or a clearly defined safe exit.
Modularity divides an algorithm into procedures or functions. It improves testing and makes assumptions explicit.
4. Pseudocode and Flowcharts
Pseudocode should expose the logic of a solution. It should identify initialization, decisions, updates, termination, and exceptional conditions. The following algorithm finds the largest value in a non-empty list.
FUNCTION maximum(values)
largest ← values[0]
FOR i ← 1 TO length(values) − 1
IF values[i] > largest THEN
largest ← values[i]
END IF
END FOR
RETURN largest
END FUNCTION
The precondition is that values contains at least one element. If an empty list is possible, the interface must define a response, such as returning an error status or using an optional result.
A flowchart provides a visual representation of control flow. Standard conventions include an oval for start or end, a rectangle for an operation, a diamond for a decision, and arrows for flow direction.
Flowchart for validating a sensor reading
Figure: Flowchart for validating a sensor reading
Figure: A simple flowchart for validating a sensor measurement.
Flowcharts are useful for communicating decisions and identifying missing branches. They become difficult to maintain when they contain excessive crossing lines or large amounts of detail. For complex behavior, a state-transition diagram or modular pseudocode is often clearer.
5. A Structured Problem-Solving Process
A reliable process separates understanding from implementation.
Step 1: Define the problem
Describe the desired behavior, stakeholders, operating environment, and success criteria. Distinguish symptoms from causes. “The robot stops unexpectedly” is a symptom; possible causes include sensor noise, a timeout, a safety interlock, or a power fault.
Step 2: Specify data and constraints
Define units, ranges, sampling rates, precision, communication protocols, timing limits, and failure behavior. Unit consistency is essential. A speed expressed in revolutions per minute must not be combined directly with a time expressed in seconds without conversion.
Step 3: Decompose and model
Identify modules, interfaces, states, and data transformations. Decide what detail belongs in the current model and what can be hidden behind an interface.
Step 4: Design and compare candidate algorithms
Develop more than one plausible approach when trade-offs matter. Compare simplicity, response time, memory use, robustness, scalability, and ease of verification.
Step 5: Prove or argue correctness
Use preconditions, postconditions, invariants, and test cases. A test can reveal an error but cannot establish correctness for every possible input. Reasoning and testing complement one another.
Step 6: Implement incrementally
Build small modules, use version control, and test each module before integration. In embedded systems, test both nominal behavior and fault behavior.
Step 7: Validate and maintain
Check the solution against real requirements, boundary cases, noisy data, timing constraints, and human safety. Record assumptions and update documentation when requirements change.
6. Correctness and Verification
An algorithm is partially correct if, whenever it terminates, its output satisfies the specification. It is totally correct if it is partially correct and terminates for every valid input.
A useful proof structure is:
State the precondition.
State the postcondition.
Identify a loop invariant, if iteration is used.
Show initialization: the invariant is true before the first iteration.
Show maintenance: one iteration preserves the invariant.
Show termination: the loop ends under the stated conditions.
Use the invariant and termination condition to establish the postcondition.
For the maximum algorithm, an invariant after processing positions 0 through i is: largest equals the maximum of those processed values. Initially it equals values[0]. Each iteration compares the next value and updates largest when necessary. When all values have been processed, largest is the maximum of the complete list.
Testing strategy
A robust test set includes:
typical valid inputs;
minimum and maximum permitted values;
empty or missing inputs, if possible;
duplicate values;
invalid and noisy sensor values;
transitions between operating modes;
fault and recovery conditions;
long-duration and timing tests.
For a controller, testing only steady-state conditions is inadequate. Transient behavior, communication loss, actuator saturation, and emergency stops must also be examined.
7. Complexity and Resource Analysis
Complexity describes how resource requirements grow as input size increases. Let n denote the number of input elements. Time complexity concerns the number of fundamental operations; space complexity concerns additional memory.
Big-O notation gives an asymptotic upper bound, usually ignoring constant factors and lower-order terms. For example, a loop that processes every element once has time complexity O(n). Two nested loops that each traverse n elements generally have complexity O(n2). Binary search on a sorted collection has complexity O(log n) because the search interval is approximately halved at each step.
Complexity
Typical behavior
Example
O(1)
Does not grow with input size
Accessing an indexed array element
O(log n)
Grows slowly
Binary search
O(n)
Proportional growth
Linear scan
O(n log n)
Efficient comparison sorting
Merge sort
O(n²)
Quadratic growth
Simple pairwise comparison
Big-O is not a complete performance prediction. Constants, hardware, cache behavior, input distribution, real-time deadlines, and energy consumption may matter more for a small embedded system. Worst-case complexity is particularly important when missing a deadline can create a hazard.
Worked example: searching for a target
Consider a sorted list of 1,024 values. A linear search may inspect up to 1,024 values. Binary search requires at most approximately ⌈log2(1024)⌉ = 10 comparisons when the target is absent or located at the deepest level, because 210 = 1024. Binary search is therefore attractive for large sorted data, but it requires sorted input and random access. If data arrive as an unsorted stream, a linear scan may be more appropriate.
Complexity analysis must therefore be connected to requirements rather than treated as a competition for the smallest notation.
8. Algorithmic Patterns in Mechatronics
Sensor validation and filtering
A measurement-processing algorithm may reject values outside physical limits, identify stale timestamps, and mark communication failures. A moving average can reduce random noise, but it introduces delay. If the window contains k samples, the simple computation of each average has time complexity O(k); a running-sum implementation can update each new average in O(1) time while using O(k) storage for the window.
Filtering must not conceal dangerous conditions. A fault detector should preserve an explicit quality or validity status rather than returning only a smoothed number.
State machines
A finite-state machine represents modes and permitted transitions. A conveyor controller might contain IDLE, RUNNING, JAMMED, and EMERGENCY_STOP. Each state defines valid outputs and transition conditions. This is safer than scattering unrelated Boolean flags throughout a program, because illegal combinations can be identified explicitly.
Feedback control as an algorithmic process
At each sampling instant, a controller measures the plant, computes an error, determines an actuator command, applies limits, and records diagnostic information. The algorithm must respect sampling time, actuator saturation, sensor validity, and safe shutdown behavior. Control design itself requires mathematical modeling, but computational thinking determines how measurements, decisions, and faults are organized in software.
The following is an illustrative case, not a report of a particular installation.
Background
A manufacturing cell receives parts on a conveyor. A photoelectric sensor detects arrival, a camera estimates dimensions, and a pneumatic actuator directs each part to an accepted or rejected bin.
Problem
The initial design occasionally rejects valid parts and sometimes activates the actuator when the camera result belongs to a previous part. The system must classify parts reliably and prevent unsafe or mistimed actuation.
Analysis
The problem is decomposed into detection, measurement, validation, classification, tracking, actuation, and fault handling. Relevant constraints include conveyor speed, camera latency, actuator response time, and the maximum allowable distance between detection and the diverter. Each part requires an identifier or position record so that results cannot be confused.
WHEN arrival sensor changes from inactive to active
create a new PartRecord
assign a unique identifier
timestamp the detection
request camera measurement
END WHEN
WHEN camera result arrives
locate the matching PartRecord using its identifier
IF measurement is invalid or outside calibrated limits THEN
classification ← UNKNOWN
ELSE IF dimensions satisfy acceptance limits THEN
classification ← ACCEPT
ELSE
classification ← REJECT
END IF
END WHEN
AT each control cycle
update estimated position of every tracked part
IF a part reaches the diverter position THEN
IF classification = ACCEPT THEN
command the accept route
ELSE IF classification = REJECT THEN
command the reject route
ELSE
command the safe-fault route
END IF
mark actuationState as COMPLETE
END IF
IF a record exceeds its maximum lifetime THEN
raise a tracking fault
END IF
END CYCLE
Correctness considerations
The matching identifier establishes the invariant that a camera result is assigned only to the corresponding part. The lifetime limit prevents obsolete records from remaining indefinitely. The UNKNOWN classification avoids treating missing data as acceptance. Position tracking must use calibrated units and account for conveyor speed; if speed varies, encoder feedback is preferable to assuming constant speed.
Outcome
The redesigned logic separates acquisition from classification and classification from actuation. It makes invalid measurements explicit, prevents indefinite waiting, and permits each module to be tested independently. Expected benefits include fewer false rejections, improved traceability, and safer fault behavior.
Learning points
The case illustrates that many failures attributed to “software bugs” originate in incomplete problem formulation. Decomposition, identifiers, explicit states, timing assumptions, and fault policies are algorithm-design decisions with direct physical consequences.
10. Limitations, Ethics, and Contemporary Practice
Algorithms operate within assumptions. A classification algorithm may perform poorly when lighting changes; a sensor-validation rule may reject legitimate conditions; and a complexity improvement may increase implementation risk. Engineers should document assumptions, calibrate instruments, quantify uncertainty where feasible, and define fallback behavior.
Safety-critical systems require hazard analysis, independent verification, traceability, controlled changes, and appropriate regulatory compliance. An algorithm should fail in a controlled state rather than silently produce an apparently valid result. Human operators must be informed when data are uncertain or a system has entered degraded operation.
Data-driven and AI-based methods can support anomaly detection, vision inspection, and predictive maintenance. They do not eliminate the need for computational thinking. The engineer must still define the problem, select relevant data, assess bias and representativeness, validate performance under operating conditions, and specify what happens when the model is uncertain. Training accuracy alone is not evidence of safe deployment. Explainability, cybersecurity, privacy, and protection against adversarial or corrupted inputs may also be relevant.
Best practice is to combine algorithmic simplicity with disciplined engineering: use clear interfaces, meaningful names, bounded loops, explicit units, defensive validation, automated tests, version control, code review, logging, and documented assumptions. Optimize only after measuring performance, and never trade away a safety requirement for speed or convenience.
Chapter Summary
Computational thinking provides a systematic bridge between an engineering problem and an executable solution. Decomposition divides complexity into modules; abstraction selects relevant detail; pattern recognition enables reuse; and algorithm design specifies precise procedures. Algorithms are commonly expressed through sequence, selection, iteration, and modularity, using pseudocode, flowcharts, or state models.
A structured process begins with problem definition and proceeds through specification, modeling, design, correctness reasoning, implementation, testing, and validation. Preconditions, postconditions, loop invariants, and termination arguments support correctness. Complexity analysis describes how time and memory requirements grow, but engineering decisions must also consider deadlines, hardware, energy, reliability, and safety. In mechatronics, explicit state management, sensor validity, timing, traceability, and fault handling are essential. Contemporary AI methods can extend computational systems, but they require the same discipline of specification, verification, ethical assessment, and safe deployment.
Key Terms
Computational thinking: A systematic approach to formulating and solving problems using computational principles.
Decomposition: Breaking a complex problem into smaller related subproblems.
Abstraction: Representing relevant features while hiding unnecessary detail.
Pattern recognition: Identifying repeated structures or behaviors that support reuse.
Algorithm: A finite, ordered, unambiguous procedure for solving a problem.
Pseudocode: Language-independent notation for expressing algorithmic logic.
Flowchart: A graphical representation of operations and control flow.
Sequence: Execution of instructions in a specified order.
Selection: Choosing a path based on a condition.
Iteration: Repeating a set of instructions.
Module: A cohesive, replaceable unit with a defined responsibility and interface.
Precondition: A condition assumed before an algorithm begins.
Postcondition: A condition expected after successful completion.
Invariant: A property that remains true during an iterative process.
Correctness: Conformance of an algorithm’s behavior to its specification.
Termination: Completion of an algorithm or bounded execution cycle.
Time complexity: The growth of computational work with input size.
Space complexity: The growth of additional memory requirements with input size.
State machine: A model consisting of states, events, actions, and transitions.
Edge case: An unusual or boundary input that tests the limits of an algorithm.
Review Questions
Short Answer Questions
Define computational thinking and name its four principal practices.
What is the difference between an algorithm and a program?
Why should a sensor value be accompanied by a validity status in a mechatronic system?
Distinguish a precondition from a postcondition.
What information does Big-O notation communicate?
Long Answer Questions
Explain how decomposition and abstraction can be applied to an automated manufacturing cell.
Describe sequence, selection, iteration, and modularity, giving a mechatronics example of each.
Explain how loop invariants contribute to an argument for algorithm correctness.
Compare linear search and binary search, including their assumptions and time complexities.
Discuss why testing alone cannot establish correctness for every possible input.
Analytical / Application Questions
Design pseudocode for a temperature-monitoring module that validates readings, detects an over-temperature condition, and enters a safe state when communication is lost. State its assumptions and edge cases.
A robot receives parts at irregular intervals and camera results may arrive out of order. Propose a data structure and algorithm that associate each result with the correct part. Explain how you would verify correctness.
An engineer replaces a simple bounded rule-based inspection algorithm with an AI classifier. Analyze the additional requirements for data quality, validation, explainability, cybersecurity, and safe fallback behavior.
Multiple Choice Questions with Answers
Question 1
Which activity is an example of decomposition?
A. Choosing only the details relevant to a model
B. Breaking a sorting cell into sensing, classification, actuation, and fault-handling modules
C. Writing instructions in a particular programming language
D. Measuring the execution time of a program
Correct Answer: B. Breaking a sorting cell into sensing, classification, actuation, and fault-handling modules
Question 2
Which property requires that an algorithm’s steps be sufficiently precise to interpret consistently?
A. Definiteness
B. Generality
C. Modularity
D. Abstraction
Correct Answer: A. Definiteness
Question 3
What is the principal purpose of a loop invariant?
A. To specify the programming language used by a loop
B. To guarantee that a loop uses constant memory
C. To state a property preserved during iteration for reasoning about correctness
D. To eliminate the need for testing
Correct Answer: C. To state a property preserved during iteration for reasoning about correctness
Question 4
What is the typical time complexity of scanning every item in an unsorted list once?
A. O(1)
B. O(log n)
C. O(n)
D. O(n2)
Correct Answer: C. O(n)
Question 5
Binary search requires which condition?
A. The collection must be sorted and support suitable access to its elements
B. The collection must contain no duplicate values
C. The collection must be stored in a linked list
D. The target must be larger than the first element
Correct Answer: A. The collection must be sorted and support suitable access to its elements
Question 6
In a flowchart, which symbol conventionally represents a decision?
A. Rectangle
B. Oval
C. Diamond
D. Circle
Correct Answer: C. Diamond
Question 7
For the maximum-value algorithm described in the chapter, what is the necessary precondition?
A. The list is sorted
B. The list contains at least one element
C. All values are positive
D. All values are distinct
Correct Answer: B. The list contains at least one element
Question 8
Why is an explicit UNKNOWN classification useful in the sorting-cell case?
A. It guarantees that every part is accepted
B. It treats missing data as a valid measurement
C. It prevents invalid or missing measurements from being silently treated as acceptance or rejection
D. It removes the need for part identifiers
Correct Answer: C. It prevents invalid or missing measurements from being silently treated as acceptance or rejection
Question 9
If a list has 1,024 elements, approximately how many halvings are needed to reduce it to one element?
A. 5
B. 10
C. 100
D. 1,024
Correct Answer: B. 10
Question 10
Which statement about AI-based inspection is most appropriate?
A. High training accuracy alone proves safe deployment
B. AI removes the need to define edge cases
C. AI systems still require validation, uncertainty handling, and safe fallback behavior
D. AI systems cannot be used in mechatronics
Correct Answer: C. AI systems still require validation, uncertainty handling, and safe fallback behavior