Count Zeroes in an Array
excerpt: This covers the basic building blocks, Counter, Capturing Return Value from Subproblem, Processing Return Value from Subproblem and Head Recursion. tags: counter capturing-return-value-from-subproblem processing-return-value-from-subproblem head-recursion
Write a function to count the number of zeroes in an input array.
Iterative Implementation
The iterative implementation to count zeroes in the input array:
|
|
Recursive Implementation
The recursive implementation to count zeroes in the input array:
|
|
Using a variable such as count is not a good programming practice. We can implement a recursive method that does not use any count variable by using head recursion.
|
|
The unit of work is performed after the recursive call. The output of the subproblem is captured in the zeroes local variable. The return value now is the number of zeroes. This implementation leans more towards functional programming. The focus is on the input and output to the recursive function. There is no mutation of state outside of the recursive function. This approach is a better coding practice.
Building Blocks
- Counter
- Capturing Return Value from Subproblem
- Processing Return Value from Subproblem
- Head Recursion