While doing exercise 1.12 from Structure and Interpretation of Computer Programs, I needed to learn an interesting technique for recursion. How does one write a nested loop in functional programming, i.e. recursively?

For example, consider this 2-dimensional loop:

How would this loop look in Scheme? Think of the problem in these steps:

1. You will only write one function. (You don’t need to write a function for every for loop.)
2. Every looping variable, along with any other state that changes along the course of the operation, must become a parameter to the function.
3. Every for loop becomes an if statement which helps the function determine where it is in the process.

This is the final product in Scheme:

The output of both programs should be identical.