Implement and Explain Four Programming Paradigms to Solve an Array Function
Implement and Explain Four Programming Paradigms to Solve an Array Function
Answer:
1
The imperative paradigm focuses on “how” to achieve the solution by providing step-by-step
instructions. It uses loops, variables, and control structures to manipulate program state.
Implementation:
Explanation:
The program explicitly defines variables (sum and average) and uses a for loop to iterate through
each element in the array.
Each step is manually controlled: summing up elements, dividing by the count, and printing the
result.
This approach closely mirrors how computers execute instructions at a low level.
The object-oriented paradigm organizes code into objects that encapsulate data (attributes) and
behavior (methods). It emphasizes reusability, modularity, and abstraction.
Implementation:
2
Explanation:
The ArrayOperations class encapsulates both data (numbers) and behavior (calculateAverage
method).
The calculateAverage method abstracts away the logic for calculating averages.
The functional paradigm treats computation as the evaluation of mathematical functions without
changing state or mutable data. It emphasizes immutability and higher-order functions.
Implementation:
def calculate_average(numbers):
# Input array
3
print("Average:", calculate_average(numbers))
Explanation:
The reduce function applies a lambda function iteratively to compute the sum of all elements in
the list.
The calculation avoids mutable variables like sum, adhering to functional principles.
The declarative paradigm focuses on “what” needs to be done rather than “how” it should be done. SQL
queries or high-level abstractions like LINQ in C# are examples.
Implementation:
// Input array
const calculateAverage = arr => arr.reduce((sum, num) => sum + num) / arr.length;
console.log("Average:", calculateAverage(numbers));
Explanation:
The code specifies what needs to happen (reduce sums up values; division calculates average),
leaving how it happens abstracted away.
Built-in methods like reduce() handle iteration internally without explicit loops or state
management.