← Programming Concepts in Mechanical Engineering (25ME34I)
Algorithms and Flowcharts
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
After studying this chapter you will be able to:
• Explain the importance of programming in solving engineering problems.
• State the advantages of Python over other programming languages.
• Define an algorithm, list its characteristics and write algorithms for simple problems.
• Identify standard flowchart symbols and draw flowcharts for sequence, decision and loop problems.
• Convert an algorithm and flowchart into a working Python program.
1.1 What is Programming?
A program is a set of instructions written in a language that a computer can understand. Programming is the process of designing, writing, testing and correcting these instructions so that the computer performs a desired task. The computer itself has no intelligence; it simply follows the instructions exactly, very fast and without getting tired. The intelligence lies in the programmer who breaks a problem into precise steps.
Think of a CNC part program. The machine does not "know" how to turn a shaft; the G-code tells it every move, feed and speed. A Python program does the same for calculations, data handling and control of hardware.
1.2 Importance of Programming in Solving Engineering Problems
Mechanical engineers deal with numbers all the time: loads, stresses, temperatures, flow rates, dimensions, tolerances and costs. Many of these calculations are repetitive. Programming turns a repetitive manual job into an automatic one.
Areas where a mechanical engineer uses programming:
• Design calculations: shaft diameter, bolt sizes, beam deflection, gear ratios, spring design.
• Thermal and fluid systems: heat transfer, pump selection, pipe-friction losses, efficiency of engines.
• Manufacturing: CNC part programming, machining-time and cost estimation, production scheduling.
• Quality control: control charts, process capability, sampling inspection, statistical analysis.
• Robotics and automation: controlling motors, reading sensors, PLC and Raspberry Pi based systems.
• Simulation: Finite Element Analysis (FEA), Computational Fluid Dynamics (CFD), kinematic simulation.
• Data analysis: condition monitoring of machines, predictive maintenance, test-rig data.
Benefits of programming for engineers:
• Speed: a program evaluates thousands of design cases in seconds.
• Accuracy: once correct, a program never makes arithmetic mistakes.
• Repeatability: the same calculation is done the same way every time.
• Automation: machines and processes can run without continuous human attention.
• Handling large data: sensor readings collected every second can be stored and analysed.
• Better decisions: graphs and statistics reveal trends that are hidden in raw numbers.
Example. A quality inspector measures the diameter of 5 shafts every hour for 25 hours, i.e. 125 readings. Calculating averages, ranges and control limits by hand takes more than an hour and invites errors. A 20-line Python program does it in a fraction of a second and also draws the control chart (Chapter 10).
1.3 Importance of Python in Problem Solving
Python is a high-level, general-purpose, interpreted programming language created by Guido van Rossum and first released in 1991. Today it is one of the most widely used languages in engineering, science, data analysis, artificial intelligence and automation. It is also the official language of the Raspberry Pi (the "Pi" in the name comes from Python).
Reasons why Python is preferred for engineering problem solving:
1. Simple and readable syntax. Python code reads almost like English. Indentation replaces braces, so programs look neat.
2. Fewer lines of code. A task needing 10 lines in C or Java often needs 2–3 lines in Python.
3. Interpreted language. Code runs line by line; errors are shown immediately, which helps beginners.
4. Huge collection of libraries: NumPy (arrays, matrices), Matplotlib (graphs), pandas (tables, Excel/CSV), SciPy (engineering mathematics, statistics), SymPy (symbolic maths), OpenCV (vision), gpiozero (Raspberry Pi hardware).
5. Free and open source, available on Windows, Linux, macOS and Raspberry Pi.
6. Platform independent: the same program runs on a laptop and on a Raspberry Pi.
7. Supports all programming styles: procedural, object-oriented and functional.
8. Excellent for hardware: direct control of GPIO pins, sensors and motors on Raspberry Pi.
9. Large community: answers, tutorials and ready code are easy to find.
Comparison of Python with C/C++ and Java
| Feature | Python | C / C++ | Java |
|---|---|---|---|
| Type | Interpreted | Compiled | Compiled to byte code + JVM |
| Ease of learning | Very easy | Difficult | Moderate |
| Syntax | Simple, indentation based | Complex, braces and semicolons | Verbose, braces |
| Variable declaration | Not required (dynamic typing) | Required (static typing) | Required (static typing) |
| Program length | Short | Long | Long |
| Development speed | Fast | Slow | Moderate |
| Execution speed | Slower | Fastest | Fast |
| Engineering libraries | Excellent (NumPy, SciPy, Matplotlib) | Limited, need extra setup | Good |
| Hardware (Raspberry Pi) | Native support | Possible, harder | Possible, harder |
Same task in three languages – display a message:
print("Hello Mechanical Engineers")Hello Mechanical Engineers
/* C program */
#include <stdio.h>
int main() {
printf("Hello Mechanical Engineers");
return 0;
}// Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello Mechanical Engineers");
}
}Python needs only one line, while C needs five and Java needs five with a class definition. This is why Python is called a "beginner-friendly but professional" language.
For the question "Compare how Python with its libraries is more advantageous than C++ or Java", write at least six points from the table above and mention specific libraries: NumPy, Matplotlib, pandas, SciPy. Add the one-line example.
1.4 Steps in Problem Solving (Program Development Cycle)
Before writing any program, a good engineer follows a sequence of steps:
1. Understand the problem – what is given (input) and what is required (output)?
2. Analyse – identify formulas, conditions and constraints.
3. Design the solution – write the algorithm and draw the flowchart.
4. Code – translate the algorithm into Python.
5. Test and debug – run with known values and remove errors.
6. Document and maintain – add comments and improve the program when needed.
Importance of breaking a problem into smaller steps
A large engineering problem, such as designing a gear drive, cannot be solved in one stroke. It is broken into smaller tasks: find the power, choose the material, calculate the module, check the bending stress, check the wear load. This approach, called stepwise refinement or top-down design, helps because:
• Each small step is simple, so it is easy to write and check.
• Errors can be located quickly in a particular step.
• Steps can be reused in other programs (for example, a function to compute stress).
• Different team members can work on different steps.
• The final solution is clear, efficient and easy to explain to others.
1.5 Algorithm
An algorithm is a finite sequence of clear, well-defined, step-by-step instructions to solve a given problem. The word comes from the name of the 9th-century Persian mathematician al-Khwarizmi. A cooking recipe, the procedure for a tensile test and the sequence for starting a diesel engine are everyday algorithms.
Characteristics of a good algorithm
| Characteristic | Meaning |
|---|---|
| Input | Zero or more quantities are supplied from outside. |
| Output | At least one result is produced. |
| Definiteness | Every step is clear and unambiguous. |
| Finiteness | The algorithm must end after a finite number of steps. |
| Effectiveness | Every step is simple enough to be carried out exactly (by hand, in principle). |
| Generality | It should work for all valid sets of input, not for one case only. |
Advantages of algorithms
• It is a step-wise, language-independent description of the solution.
• It makes writing the program easy, since each step becomes one or two lines of code.
• It helps in finding logical errors before coding (debugging on paper).
• It improves logical thinking and is easy to communicate to others.
Disadvantages of algorithms
• Writing algorithms for large problems is time consuming.
• Branching and looping are not as easy to visualise as in a flowchart.
General steps in writing an algorithm
1. Start.
2. Read (input) the required data.
3. Perform the calculations or processing.
4. Check conditions, if any, and choose the action.
5. Repeat steps, if needed.
6. Display (output) the result.
7. Stop.
Example 1.1 – Algorithm to find the area of a circle.
1. Start.
2. Read radius r.
3. Compute area A = π × r × r.
4. Display A.
5. Stop.
Pseudocode
Pseudocode is an algorithm written in a form close to a programming language but without strict syntax. It is a bridge between the algorithm and the program.
BEGIN
READ r
A <- 3.1416 * r * r
PRINT A
END1.6 Flowchart
A flowchart is a pictorial (graphical) representation of an algorithm using standard symbols connected by arrows. The symbols show the type of operation and the arrows show the order in which operations are carried out. Flowcharts are standardised by ANSI and ISO 5807.
Fig. 1.1 Standard flowchart symbols
Rules for drawing flowcharts
• Every flowchart has exactly one Start and at least one Stop terminal.
• The flow is generally top to bottom and left to right.
• Use only standard symbols; write brief statements inside them.
• A process box has one entry and one exit.
• A decision box has one entry and two exits (Yes/No or True/False), which must be labelled.
• Flow lines must not cross; use connectors when the chart is long.
• The flowchart must be neat, simple and easy to follow.
Flowchart methodology (procedure)
1. Understand the problem: identify inputs, process and outputs.
2. Write the algorithm in steps.
3. Select appropriate symbols for each step: terminal for start/stop, parallelogram for read/print, rectangle for calculation, diamond for condition.
4. Arrange and connect the symbols with flow lines in logical order.
5. Verify the flowchart by "dry running" it with sample values: check that every path reaches Stop.
Advantages of flowcharts
• Logic is easy to understand at a glance (a picture is worth a thousand words).
• Good for communication among engineers and programmers.
• Serves as a blueprint for coding and as documentation.
• Helps in debugging and in finding missing steps.
Limitations of flowcharts
• Drawing flowcharts for complex programs is laborious.
• Any change in logic may require redrawing the whole chart.
• There is no standard for the amount of detail to be shown.
Algorithm vs Flowchart
| Algorithm | Flowchart |
|---|---|
| Step-by-step description in words | Graphical representation with symbols |
| Easy to write, harder to visualise | Takes time to draw, easy to understand |
| Suitable for large problems | Suitable for small and medium problems |
| No standard symbols | Uses standard ANSI/ISO symbols |
| Easy to modify | Modification may need redrawing |
1.7 The Three Basic Programming Structures
Every program, however large, is built from only three control structures.
Fig. 1.2 Sequence, selection and iteration structures
| Structure | Meaning | Python keyword | Example |
|---|---|---|---|
| Sequence | Steps are executed one after another | (normal statements) | Fahrenheit to Centigrade |
| Selection (decision) | One of two or more paths is chosen based on a condition | if, elif, else | Maximum of three forces |
| Iteration (loop) | A group of steps is repeated | for, while | Multiplication table |
1.8 Practice Programs (Week 1)
Program 1.1 – Convert Fahrenheit to Centigrade (Sequence)
Formula: C = (F − 32) × 5 / 9
Algorithm
1. Start.
2. Read temperature in Fahrenheit, F.
3. Compute C = (F − 32) × 5 / 9.
4. Display C.
5. Stop.
Fig. 1.3 Flowchart: Fahrenheit to Centigrade
# Program 1.1: Fahrenheit to Centigrade
f = float(input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5 / 9
print("Temperature in Centigrade =", round(c, 2), "°C")Enter temperature in Fahrenheit: 98.6 Temperature in Centigrade = 37.0 °C
Explanation: input() reads the value as text, float() converts it into a decimal number, the formula is evaluated and round(c, 2) shows two decimal places. Body temperature 98.6 °F equals 37 °C.
Program 1.2 – Efficiency of a Simple Machine (Sequence)
For a simple lifting machine (screw jack, pulley block, wheel and axle):
• Mechanical Advantage MA = Load (W) / Effort (P)
• Velocity Ratio VR = distance moved by effort / distance moved by load
• Efficiency η = (MA / VR) × 100 %
Algorithm
1. Start.
2. Read load W, effort P and velocity ratio VR.
3. Compute MA = W / P.
4. Compute η = (MA / VR) × 100.
5. Display MA and η.
6. Stop.
Fig. 1.4 Flowchart: efficiency of a simple machine
# Program 1.2: Efficiency of a simple machine
W = float(input("Enter load lifted W (N): "))
P = float(input("Enter effort applied P (N): "))
VR = float(input("Enter velocity ratio VR: "))
MA = W / P
eff = (MA / VR) * 100
print("Mechanical Advantage =", MA)
print("Efficiency =", eff, "%")Enter load lifted W (N): 1000 Enter effort applied P (N): 125 Enter velocity ratio VR: 10 Mechanical Advantage = 8.0 Efficiency = 80.0 %
Explanation: a load of 1000 N is lifted by an effort of 125 N, so MA = 8. With VR = 10, the efficiency is 80 %. The remaining 20 % is lost in friction. For an ideal machine MA = VR and η = 100 %.
Program 1.3 – Multiplication Table of 5 (Control Loop)
Algorithm
1. Start.
2. Setn=5andi=1.
3. If i ≤ 10, go to step 4; otherwise go to step 6.
4. Display n × i.
5. Increase i by 1 and go to step 3.
6. Stop.
Fig. 1.5 Flowchart: multiplication table of 5 using a loop
# Program 1.3: Multiplication table of 5
n = 5
for i in range(1, 11):
print(n, "x", i, "=", n * i)5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
Explanation: range(1, 11) produces the numbers 1, 2, ..., 10 (the end value 11 is not included). The body of the loop is executed ten times. The decision box "i ≤ 10?" of the flowchart is handled automatically by the for loop.
Program 1.4 – Maximum of Three Forces (Decision)
Algorithm
1. Start.
2. Read forces F1, F2, F3.
3. If F1 > F2 and F1 > F3, then MAX = F1.
4. Else, if F2 > F3, then MAX = F2.
5. Else MAX = F3.
6. Display MAX.
7. Stop.
Fig. 1.6 Flowchart: maximum of three forces
# Program 1.4: Maximum of three forces
F1 = float(input("Enter force F1 (N): "))
F2 = float(input("Enter force F2 (N): "))
F3 = float(input("Enter force F3 (N): "))
if F1 > F2 and F1 > F3:
MAX = F1
elif F2 > F3:
MAX = F2
else:
MAX = F3
print("Maximum force =", MAX, "N")Enter force F1 (N): 120 Enter force F2 (N): 150 Enter force F3 (N): 100 Maximum force = 150.0 N
Explanation: the first condition is false (120 is not greater than 150), so the programchecksF2 >F3,which istrue;henceMAX =150N. Python'sbuilt-inmax(F1, F2, F3) gives the same result in one line, but in the exam you must show the decision logic.
Program 1.5 – Check whether a Number is Prime (CIE question)
A prime number is a number greater than 1 that has no divisors other than 1 and itself. It is enough to test divisors from 2 up to √N, because if N has a factor larger than √N, it must also have one smaller than √N.
Algorithm
1. Start.
2. Read N.
3. If N < 2, display "Not Prime" and stop.
4. Set i = 2.
5. While i × i ≤ N: if N is divisible by i, display "Not Prime" and stop; otherwise increase i by 1.
6. Display "Prime".
7. Stop.
Fig. 1.7 Flowchart: prime number check
# Program 1.5: Prime number check
N = int(input("Enter a number: "))
prime = True
if N < 2:
prime = False
i = 2
while i * i <= N:
if N % i == 0:
prime = False
break
i = i + 1
if prime:
print(N, "is a Prime number")
else:
print(N, "is Not a Prime number")Enter a number: 29 29 is a Prime number
Engineering use: prime numbers of teeth are chosen for a gear and pinion pair (a "hunting tooth" design) so that the same pair of teeth do not meet repeatedly, giving even wear.
Program 1.6 – Gear System Speed and Torque (Sequence)
Fig. 1.8 Flowchart: gear system output
The algorithm is: Start → read input speed, input torque and gear ratio → output speed = input speed / G → output torque = input torque × G → display → Stop. The program is given in Chapter 2 (Program 2.2).
1.9 Solved Exam Questions
Q1. Explain the importance of programming in solving engineering problems. (6 marks)
Answer: Programming allows an engineer to instruct a computer to perform calculations and control tasks automatically. Its importance is:
• Speed: repetitive design calculations (for example, shaft diameter for 50 load cases) are completed in seconds.
• Accuracy and repeatability: a tested program gives correct results every time without arithmetic mistakes.
• Data handling: large volumes of test and sensor data can be stored, sorted and analysed.
• Visualisation: graphs such as stress-strain curves and control charts are drawn instantly.
• Automation and control: motors, pumps and robots can be controlled by programs (Raspberry Pi, PLC, CNC).
• Simulation: FEA and CFD software replaces costly physical prototypes.
• Optimisation: many design alternatives can be compared to choose the best one.
Q2. Discuss the importance of breaking down a problem into smaller steps when creating an algorithm. How does this help in developing efficient and clear solutions? (6 marks)
Answer: Breaking a problem into smaller steps (top-down design or stepwise refinement) means dividing the main task into sub-tasks that are simple enough to be solved directly. It helps because each step is easy to understand and code; errors can be traced to a particular step; steps can be reused as functions; the logic becomes clear to others; and redundant work is avoided, making the solution efficient. Example: to design a shaft, the steps are (1) find torque from power and speed, (2) find bending moment, (3) compute equivalent torque, (4) find diameter from allowable shear stress, (5) select standard size. Each step becomes a small block of code.
Q3. Define algorithm. Explain its characteristics. (5 marks)
Answer: An algorithm is a finite set of well-defined, unambiguous instructions that solve a problem in a finite number of steps. Characteristics: input (zero or more), output (at least one), definiteness (each step is clear), finiteness (it terminates), effectiveness (each step is basic and feasible) and generality (it works for all valid inputs).
Q4. Define flowchart. Draw and explain any five flowchart symbols. (6 marks)
Answer: A flowchart is a diagrammatic representation of an algorithm using standard symbols joined by flow lines. Symbols: terminal (oval/rounded rectangle) for start and stop; input/output (parallelogram) for reading data and printing results; process (rectangle) for calculations and assignments; decision (diamond) for conditions with Yes/No exits; flow line (arrow) to show direction; connector (circle) to join parts of a chart. Refer Fig. 1.1.
Q5. Draw a flowchart to find the maximum of three forces F1, F2 and F3.
Answer: Refer Fig. 1.6 and Program 1.4. The flowchart first compares F1 with both F2 and F3. If F1 is larger than both, MAX = F1. Otherwise F2 is compared with F3 and the larger one is stored in MAX. Finally MAX is printed.
Q6. Draw a flowchart to check whether a given number is prime. Include decision points and the input, process and output steps. (7 marks)
Answer: Refer Fig. 1.7 and Program 1.5. Input: N. Decision 1: N < 2 → Not Prime. Process: i = 2. Decision 2 (loop): i × i ≤ N? Decision 3: N % i == 0 → Not Prime; otherwise i = i + 1 and go back to Decision 2. When the loop ends without finding a divisor, output "Prime".
Q7. Differentiate between algorithm and flowchart.
Answer: Refer the comparison table in Section 1.6. An algorithm is text and easy to modify; a flowchart is a picture and easier to understand but harder to modify.
Q8. What are the three fundamental programming structures? Explain with examples.
Answer: Sequence – instructions execute one after another (F to C conversion). Selection – a condition decides which path is taken (finding the larger force, pass/fail). Iteration – a set of instructions is repeated (multiplication table, factorial). Every program is a combination of these three (Böhm–Jacopini structured programming theorem).
1.10 Multiple Choice Questions
1. Python was developed by a) Dennis Ritchie b) Guido van Rossum c) James Gosling d) Bjarne Stroustrup
Answer: (b) Reason: Guido van Rossum released Python in 1991. Ritchie created C, Gosling created Java and Stroustrup created C++.
2. Which flowchart symbol is used for a decision? a) Rectangle b) Parallelogram c) Diamond d) Oval
Answer: (c) Reason: A diamond has one entry and two labelled exits (Yes/No), which suits a condition check.
3. The parallelogram symbol in a flowchart represents a) Processing b) Input/Output c) Start/Stop d) Connector
Answer: (b) Reason: Reading data and printing results are shown in a parallelogram.
4. The property that an algorithm must terminate after a finite number of steps is called a) Definiteness b) Effectiveness c) Finiteness d) Generality
Answer: (c) Reason: Finiteness ensures the algorithm ends; an endless loop violates it.
5. Which of the following is NOT a characteristic of an algorithm? a) Input b) Output c) Ambiguity d) Definiteness
Answer: (c) Reason: Each step must be unambiguous (definite); ambiguity is the opposite.
6. A rectangle in a flowchart indicates a) Decision b) Process or calculation c) Input d) Terminal
Answer: (b) Reason: Calculations and assignments such as C = (F − 32) × 5/9 are written in a rectangle.
7. Python is a/an ________ language. a) Machine b) Assembly c) Interpreted high-level d) Low-level compiled
Answer: (c) Reason: Python source is executed by the interpreter line by line; it is high-level and human readable.
8. Which structure is used to print the multiplication table of 5? a) Sequence b) Selection c) Iteration d) None
Answer: (c) Reason: Printing ten lines with the same pattern requires repetition, i.e. a loop.
9. Finding the maximum of three forces is an example of a) Sequence b) Selection c) Iteration d) Recursion
Answer: (b) Reason: The path taken depends on comparisons, which is selection (decision making).
10. The efficiency of a simple machine is given by a)VR/MA×100 b)MA×VR c)MA/VR×100 d)W/P
Answer: (c) Reason: Efficiency is the ratio of mechanical advantage to velocity ratio, expressed in percent.
11. Which symbol is used to connect parts of a flowchart on the same page? a) Small circle b) Pentagon c) Diamond d) Parallelogram
Answer: (a) Reason: The on-page connector is a small circle with a letter; the off-page connector is a pentagon.
12. The main advantage of Python over C for engineering calculations is a) Faster execution b) Simple syntax and rich libraries c) Needs a compiler d) Manual memory management
Answer: (b) Reason: Python is slower than C but much quicker to write, with libraries like NumPy and Matplotlib.
13. An informal, code-like description of an algorithm is called a) Flowchart b) Pseudocode c) Machine code d) Byte code
Answer: (b) Reason: Pseudocode uses programming-like words (READ, PRINT, IF) without strict syntax.
14. How many exits does a decision symbol have? a) One b) Two c) Three d) Zero
Answer: (b) Reason: A decision has one entry and two exits, one for True and one for False.
15. 98.6 °F is equal to a) 35 °C b) 37 °C c) 39 °C d) 40 °C
Answer: (b) Reason: C = (98.6 − 32) × 5/9 = 66.6 × 5/9 = 37 °C.
16. In a prime check, divisors need to be tested only up to a) N/2 always b) √N c) N − 1 only d) 10
Answer: (b) Reason: If N had a factor larger than √N, the paired factor would be smaller than √N and already detected.
1.11 Exercises
1. Write an algorithm and draw a flowchart to calculate the power transmitted by a shaft, P = 2πNT/60.
2. Draw a flowchart to find whether a student has passed (marks ≥ 35) or failed.
3. Write an algorithm to find the sum of the first N natural numbers using a loop.
4. Draw a flowchart to compute the stress in a bar, σ = P/A, and display "Safe" if σ is less than the allowable stress.
5. Explain the flowchart methodology with the example of converting Celsius to Kelvin.