Computer Science – 11.3 Structured Programming | e-Consult
11.3 Structured Programming (1 questions)
Potential Problems:
- Lack of Reusability: The code is specific to calculating the sum of the first 'n' natural numbers. If you need to calculate the sum of a different set of numbers, you'd have to rewrite the code.
- Poor Modularity: The code is not broken down into logical units. This makes it harder to understand and maintain.
- Limited Readability: While relatively simple, the code lacks a descriptive name and doesn't clearly communicate its purpose beyond the calculation itself.
How a procedure could improve it: A procedure could encapsulate the entire calculation logic, making it reusable and more modular. The procedure would accept 'n' as a parameter and perform the summation. This would improve readability and allow the code to be easily used in other parts of a program.
Example of improved code (Conceptual - language agnostic):
| Procedure: CalculateSum |
PROCEDURE CalculateSum(n)
sum = 0
FOR i = 1 TO n
sum = sum + i
END FOR
RETURN sum
END PROCEDURE
BEGIN
result = CalculateSum(10) // Example: Calculate the sum of the first 10 natural numbers
PRINT result
END
This improved code defines a procedure CalculateSum that takes 'n' as input and returns the sum. The main part of the program then calls this procedure with the desired value of 'n'.