Chapter 2
Computational Thinking and Algorithm Design
Bachelors Program in Mechnical Engineering
Computer Programming for Engineers
•
Bachelor
Computational Thinking and Algorithm Design
Introduction
Mechanical engineers increasingly solve problems through computational models, automated experiments, data acquisition, and digital control. Before a program can calculate a stress, regulate a motor, or estimate heat loss, an engineer must convert a physical requirement into a precise computational procedure. This conversion is the work of computational thinking and algorithm design.
Computational thinking is not limited to writing code. It involves identifying the essential features of a problem, representing them appropriately, decomposing a complex task, recognizing patterns, designing a finite procedure, and evaluating whether the procedure is correct and efficient. A well-designed algorithm provides a traceable link between an engineering requirement and an implemented program.
For example, the requirement “determine whether a shaft is safe” is incomplete as a programming specification. The engineer must establish the input loads and geometry, calculate the relevant stresses, identify the material strength, define the factor of safety, specify units, and determine what output constitutes a safe or unsafe design.
Learning Objectives
By the end of this chapter, you should be able to:
Translate an engineering requirement into inputs, outputs, assumptions, and constraints.
Apply decomposition, abstraction, pattern recognition, and algorithmic reasoning.
Represent algorithms using structured English, pseudocode, and flowcharts.
Use sequence, selection, and iteration correctly.
Trace algorithms manually and identify logical errors.
Assess correctness, termination, time complexity, and space complexity.
Develop a traceable algorithm for an engineering application.
Recognize limitations, ethical risks, and the role of verification in computational work.
1. From Engineering Requirement to Computational Problem
A computational problem statement should answer six questions:
What is the purpose of the calculation?
What data are available?
What quantities must be produced?
What physical, numerical, or operational constraints apply?
What assumptions simplify the model?
How will the result be checked?
A useful specification separates inputs, outputs, constraints, and assumptions.
Element
Meaning
Example for a shaft-checking program
Input
Data supplied to the algorithm
Torque, diameter, length, material strength
Output
Information produced
Shear stress, factor of safety, decision
Constraint
Condition that must be satisfied
Diameter > 0; factor of safety ≥ required value
Assumption
Deliberate simplification
Uniform circular shaft; torsion is dominant
Validation
Evidence that the result is credible
Comparison with hand calculation or test data
An engineering requirement should also specify units. A program that receives torque in N·m and diameter in mm can produce an incorrect answer if the formula expects both quantities in a consistent system. Unit conversion is therefore part of algorithm design, not merely presentation.
Example: shaft safety requirement
Suppose a solid circular shaft is subjected to torque T. Under the assumptions of linear elastic behavior, uniform circular geometry, and pure torsion, the maximum shear stress is:
τmax = 16T ÷ (πd³)
Here, τ_max is maximum shear stress, T is torque, and d is shaft diameter. If T is expressed in N·mm and d in mm, τ_max is obtained in N/mm², which is numerically equal to MPa. If the allowable shear stress is τ_allow, the factor of safety is:
n = τallow ÷ τmax
The design is acceptable when n ≥ n_required. These equations apply only under the stated modeling assumptions; a real design may also require fatigue, stress concentration, buckling, bearing, and dynamic analyses.
A corresponding computational specification is:
Inputs: T, d, τ_allow, and n_required.
Outputs: τ_max, n, and an acceptance decision.
Constraints: T ≥ 0, d > 0, τ_allow > 0, and n_required > 0.
Procedure: validate data, calculate stress, calculate factor of safety, compare with the required value, and report results.
2. Computational Thinking
Computational thinking consists of complementary reasoning practices.
Decomposition
Decomposition divides a large problem into smaller tasks with clear interfaces. A shaft design program may be divided into:
Read or receive data.
Validate units and ranges.
Convert units if required.
Calculate stress.
Calculate factor of safety.
Compare the result with the requirement.
Report the result and warnings.
Each task can be developed and tested independently. Decomposition reduces cognitive load and makes errors easier to locate.
Abstraction
Abstraction retains details relevant to the current decision and suppresses irrelevant detail. A preliminary shaft-sizing algorithm may represent a shaft by torque and diameter. It may omit surface finish and residual stress during an early feasibility calculation, but those factors must be restored when fatigue life is assessed. Abstraction is useful only when its boundaries are explicit.
Pattern recognition
Engineers recognize recurring structures. Many programs contain the same pattern: acquire data, validate it, transform it, apply a model, and communicate a result. Recognizing this pattern supports reusable functions and consistent testing.
Algorithmic thinking
Algorithmic thinking expresses a solution as unambiguous, finite, ordered steps. An algorithm must specify what happens, when it happens, and under what conditions an alternative action is selected.
Generalization
A good solution should work for a defined class of inputs, not only for one example. A shaft-checking algorithm should accept any physically valid torque and diameter within its stated range, rather than containing values embedded for one test case.
3. Representing Algorithms
Structured English
Structured English uses ordinary language with disciplined control words. It is useful during early design because it exposes the logic without committing to a programming language.
Receive torque, diameter, allowable stress, and required factor of safety.
If any value violates its constraint, report invalid input and stop.
Calculate maximum shear stress.
Calculate factor of safety.
If the factor of safety meets the requirement, report acceptable; otherwise report unacceptable.
Display the calculated values and units.
Pseudocode
Pseudocode is a language-independent representation that resembles executable code while remaining focused on logic.
ALGORITHM CheckShaft
INPUT T, d, tau_allow, n_required
IF T < 0 OR d <= 0 OR tau_allow <= 0 OR n_required <= 0 THEN
OUTPUT "Invalid input"
STOP
END IF
tau_max ← 16 × T / (π × d³)
n ← tau_allow / tau_max
IF n >= n_required THEN
decision ← "Acceptable"
ELSE
decision ← "Unacceptable"
END IF
OUTPUT tau_max, n, decision
END ALGORITHM
Pseudocode uses assignment, shown by ←, rather than equality in a mathematical equation. The distinction prevents confusion between storing a value and asserting that two expressions are equal.
Flowcharts
A flowchart represents control flow graphically. Common symbols include an oval for start or stop, a parallelogram for input or output, a rectangle for processing, and a diamond for a decision. Arrows must show the direction of control, and decision branches should be labeled, commonly Yes and No.
Flowchart for checking shaft safety
Figure: Flowchart for checking shaft safety
Figure: A partial flowchart showing validation, calculation, and decision logic for a shaft-safety algorithm.
The flowchart is deliberately partial at the lower edge; the two final branches would report either “acceptable” or “unacceptable” and then terminate.
4. Fundamental Control Structures
Structured algorithms are built from three control structures.
Sequence
Sequence executes instructions in order. For example, units must be converted before a formula is evaluated. Reversing those operations may produce a numerically plausible but physically incorrect result.
Selection
Selection chooses among alternatives. The basic form is IF–THEN–ELSE. Conditions should be precise. “Large torque” is ambiguous; “T > 500 N·m” is testable. Boundary conditions such as equality must be considered explicitly.
Iteration
Iteration repeats a block of instructions. A FOR loop is suitable when the number of repetitions is known. A WHILE loop is suitable when repetition continues until a condition changes. Every loop requires:
initialization of control data;
a condition that can eventually become false;
an update that moves toward termination.
A loop that does not update its control variable may never terminate. In numerical engineering, an iterative method may also require a convergence criterion, such as a specified error tolerance and a maximum iteration count.
5. Correctness and Traceability
An algorithm is partially correct if, whenever it terminates, its output satisfies the specification. It is totally correct if it is partially correct and always terminates for every valid input.
Correctness can be assessed through:
Preconditions: what must be true before execution, such as d > 0.
Postconditions: what must be true after execution, such as the reported stress being calculated from the accepted inputs.
Invariants: properties that remain true during a loop.
Test cases: selected inputs with known or independently verified outputs.
A trace table records variable values after each important step. For the shaft example, let T = 120 N·m = 120,000 N·mm, d = 20 mm, τ_allow = 50 MPa, and n_required = 2.0. Then:
τmax = 16(120000) ÷ (π × 20³) ≈ 76.39 MPa
and
n = 50 ÷ 76.39 ≈ 0.65
Since 0.65 < 2.0, the result is unacceptable under the stated model. The unit conversion is essential: using 120 directly with d in millimetres would produce an answer 1,000 times too small.
Step
T (N·mm)
d (mm)
τ_max (MPa)
n
Decision
Input
120000
20
—
—
—
Stress
120000
20
76.39
—
—
Safety
120000
20
76.39
0.65
—
Compare
120000
20
76.39
0.65
Unacceptable
Testing should include normal values, boundary values, invalid values, extreme values, and cases where the expected decision changes. Testing cannot prove that an algorithm is correct for every possible input, but systematic tests can expose defects and support confidence.
6. Computational Complexity
Computational complexity describes how resource requirements grow as input size grows. The input size is represented by n, although n may mean the number of measurements, nodes, or elements rather than a physical dimension.
Big-O notation describes an upper-order growth rate while ignoring constants and lower-order terms. For example, an algorithm requiring 3n + 10 operations is O(n), while one requiring n² + 4n is O(n²).
Complexity
Typical interpretation
Example
O(1)
Constant time
Read one array element
O(log n)
Logarithmic growth
Binary search in sorted data
O(n)
Linear growth
Scan all measurements
O(n log n)
Efficient sorting growth
Merge sort
O(n²)
Pairwise growth
Compare every pair of measurements
Complexity is not the same as execution time. Hardware, implementation language, memory access, and constants also matter. Nevertheless, complexity is valuable when selecting an algorithm for large data sets.
Space complexity measures additional memory requirements. An algorithm that scans n measurements using a fixed number of variables may use O(1) auxiliary space, whereas one that stores a second copy uses O(n) additional space.
For engineering programs, numerical stability is another form of computational quality. An algorithm may have good time complexity but produce unreliable results because of round-off error, ill-conditioned equations, inappropriate tolerances, or overflow. Complexity analysis must therefore be combined with numerical verification.
7. Applied Case: Automated Temperature-Alarm System
The following is an illustrative case, not a report of a specific industrial installation.
Background
A test rig contains a bearing whose temperature is measured every second. Excessive temperature may indicate inadequate lubrication or impending failure. The system must alert an operator when the temperature exceeds a permitted limit.
Problem
A simple requirement such as “alarm when the bearing is too hot” is inadequate. Sensor noise could cause repeated alarm and reset events. The specification must define the measurement unit, threshold, sampling interval, and reset behavior.
Assume the following design:
temperature input is in °C;
alarm threshold is 85 °C;
the alarm activates after three consecutive readings at or above 85 °C;
the alarm resets only after three consecutive readings below 80 °C;
invalid or missing readings cause a sensor fault message.
The gap between activation and reset thresholds is called hysteresis. It reduces rapid switching near the limit.
Algorithm
ALGORITHM BearingMonitor
high_count ← 0
low_count ← 0
alarm ← FALSE
REPEAT for each sensor reading
INPUT temperature
IF temperature is missing OR temperature is outside sensor range THEN
OUTPUT "Sensor fault"
CONTINUE
END IF
IF temperature >= 85 THEN
high_count ← high_count + 1
low_count ← 0
ELSE IF temperature < 80 THEN
low_count ← low_count + 1
high_count ← 0
ELSE
high_count ← 0
low_count ← 0
END IF
IF high_count >= 3 THEN
alarm ← TRUE
END IF
IF low_count >= 3 THEN
alarm ← FALSE
END IF
OUTPUT alarm
END REPEAT
END ALGORITHM
Analysis
The state variables high_count, low_count, and alarm provide memory between readings. The algorithm uses selection and iteration. Each reading requires a fixed number of operations, so the processing time per reading is O(1), and the memory requirement is O(1).
A trace beginning with valid readings of 86, 87, and 85 °C activates the alarm on the third reading. If the subsequent readings are 83, 81, and 79 °C, the alarm does not reset until the third reading below 80 °C. The 83 and 81 °C readings reset the low counter because they lie in the hysteresis band.
Outcome and learning points
The case demonstrates that algorithm design includes operational definitions, state management, invalid-data handling, and safety behavior. In an actual system, the engineer would also specify watchdog behavior, sensor redundancy, fail-safe outputs, data logging, cybersecurity, calibration, and compliance with applicable machinery and functional-safety standards.
8. Professional, Ethical, and Contemporary Considerations
A computational result is not automatically a reliable engineering decision. Engineers are responsible for identifying assumptions, preserving units, documenting versions, and ensuring that users understand model limitations. A program should not silently replace missing data with zero when zero has a physical meaning.
Safety-related software requires stronger controls than a classroom script. These may include requirements traceability, code review, independent verification, change control, test records, access control, and audit logs. When a model influences a safety decision, the responsible engineer must retain human oversight and provide a clear basis for the decision.
AI-assisted programming can generate pseudocode or code rapidly, but generated code may contain incorrect formulas, hidden assumptions, insecure input handling, or unsuitable numerical methods. AI output must be reviewed against engineering requirements, tested with independent cases, and documented. An AI system is an aid to reasoning, not evidence that a design is correct.
Best practices include:
Define the problem before selecting a programming language.
State units, assumptions, valid ranges, and boundary conditions.
Use meaningful variable names and modular procedures.
Separate input validation, calculation, and reporting.
Compare important results with hand calculations or trusted references.
Test normal, boundary, invalid, and extreme cases.
Record requirements and link them to tests and outputs.
Report uncertainty and limitations rather than implying false precision.
Chapter Summary
Computational thinking translates engineering needs into structured, solvable problems. The essential specification identifies inputs, outputs, constraints, assumptions, units, and validation methods. Decomposition divides complex tasks; abstraction manages relevant detail; pattern recognition supports reuse; and algorithmic thinking creates finite, unambiguous procedures.
Pseudocode and flowcharts communicate logic before implementation. Sequence, selection, and iteration form the basic control structures. Correctness is supported by preconditions, postconditions, invariants, trace tables, and systematic testing. Big-O notation describes how time and memory requirements grow, but numerical stability and physical validity must also be considered. Finally, professional computation requires traceability, independent verification, responsible use of AI, and explicit communication of limitations.
Key Terms
Computational thinking: A method of solving problems through decomposition, abstraction, pattern recognition, and algorithmic reasoning.
Algorithm: A finite, ordered, unambiguous procedure for solving a problem.
Input: Data supplied to an algorithm.
Output: Information produced by an algorithm.
Constraint: A condition that valid data or solutions must satisfy.
Assumption: A stated simplification or condition used in a model.
Decomposition: Division of a complex problem into manageable subproblems.
Abstraction: Representation that retains relevant features while omitting unnecessary detail.
Pseudocode: Language-independent description of algorithmic logic.
Flowchart: Graphical representation of control flow.
Sequence: Execution of instructions in order.
Selection: Choice between alternative paths based on a condition.
Iteration: Repeated execution of instructions.
Precondition: Requirement that must hold before an algorithm or procedure begins.
Postcondition: Property expected after successful completion.
Invariant: Property maintained during execution, especially within a loop.
Trace table: Record of variable values during an algorithm’s execution.
Computational complexity: Growth of resource requirements as input size increases.
Hysteresis: Use of different activation and reset thresholds to prevent rapid switching.
Traceability: Ability to link requirements, procedures, calculations, tests, and results.
Review Questions
Short Answer Questions
Distinguish an input, an output, a constraint, and an assumption in an engineering algorithm.
What are the three fundamental control structures?
Why are units part of algorithm design?
Define a loop invariant.
What does O(n) mean in complexity analysis?
Long Answer Questions
Explain how decomposition and abstraction can be applied to an automated mechanical-testing system.
Compare pseudocode and flowcharts as tools for communicating algorithm design.
Explain partial correctness and total correctness, including the role of termination.
Describe a systematic testing strategy for an engineering calculation program.
Discuss why an algorithm with low computational complexity may still produce an unsafe engineering result.
Analytical / Application Questions
Design pseudocode for a program that reads ten force measurements, rejects negative values, calculates the average of valid measurements, and reports whether the average exceeds a specified limit. State how your algorithm handles the case in which no valid measurements exist.
A program converts a diameter from millimetres to metres and then applies a formula requiring millimetres. Identify the likely consequence and propose two verification methods.
Design a temperature-monitoring algorithm with an activation threshold, a reset threshold, and a maximum allowed number of invalid readings. Explain the states, boundary conditions, and tests needed to establish confidence in the design.
Multiple Choice Questions with Answers
Question 1
Which item is an example of a constraint in an engineering algorithm?
A. The calculated shaft stress
B. The requirement that diameter must be greater than zero
C. The programming language used
D. The engineer who wrote the program
Correct Answer: B. The requirement that diameter must be greater than zero
Question 2
Which computational-thinking practice divides a complex problem into smaller tasks?
A. Decomposition
B. Compilation
C. Encryption
D. Iteration
Correct Answer: A. Decomposition
Question 3
In a flowchart, which symbol conventionally represents a decision?
A. Rectangle
B. Parallelogram
C. Diamond
D. Oval
Correct Answer: C. Diamond
Question 4
What is the principal danger of a loop that never changes its control variable?
A. It necessarily uses O(1) memory
B. It may fail to terminate
C. It always produces a syntax error
D. It converts all inputs to strings
Correct Answer: B. It may fail to terminate
Question 5
For T = 120000 N·mm and d = 20 mm, what is the approximate torsional shear stress from τ = 16T ÷ (πd³)?
A. 0.076 MPa
B. 7.64 MPa
C. 76.4 MPa
D. 764 MPa
Correct Answer: C. 76.4 MPa
Question 6
An algorithm that scans each of n measurements once generally has what time complexity?
A. O(1)
B. O(log n)
C. O(n)
D. O(n²)
Correct Answer: C. O(n)
Question 7
What is the purpose of a trace table?
A. To record variable values during execution
B. To convert units automatically
C. To replace all testing
D. To encrypt source code
Correct Answer: A. To record variable values during execution
Question 8
In the temperature case, why are separate activation and reset thresholds used?
A. To increase memory use
B. To create hysteresis and reduce rapid switching
C. To eliminate sensor calibration
D. To guarantee zero measurement error
Correct Answer: B. To create hysteresis and reduce rapid switching
Question 9
Which property must be established in addition to partial correctness for total correctness?
A. Termination
B. A graphical interface
C. Parallel execution
D. Constant input size
Correct Answer: A. Termination
Question 10
Why must AI-generated engineering code be independently reviewed?
A. AI code is always too slow
B. Generated code may contain incorrect assumptions or formulas
C. Review makes units unnecessary
D. AI cannot produce pseudocode
Correct Answer: B. Generated code may contain incorrect assumptions or formulas
Computer Programming for Engineers
Chapter 2
of 15