Instead of looping from 1 to 5000, you define the relationship instead:
sum(1,n) = 1 + n + sum(2, n-1).
Isn't this clearer to understand problem first, instead of just looping ?
Instead of looping from 1 to 5000, you define the relationship instead:
sum(1,n) = 1 + n + sum(2, n-1).
Isn't this clearer to understand problem first, instead of just looping ?
The concept of a loop (i.e. doing something over and over as long as a condition is true) is (again IMHO) a much simpler concept than recursion.
The university I worked at tried moving functional programming into the first semester. Let's just say, that didn't work out at all. The imperative programming style is apparently much easier for students to grasp.
Edit: The more I think about it, it seems to me that a loop is clearer because the initial state, upon which you iterate on, is much more obvious. Where with recursion, I primarily see the step, but not where exactly I started from -- if that makes any sense..
Instead of looping from 1 to 5000, you compute (1 + 5000) * 5000 / 2
This is what "understand problem first" actually means
sum(n) = is_even(n) ? n/2 * (n+1) : (n+1)/2 * n
because of one n and n+1 will always be even. But it show that unfortunately things are often not as straightforward as they first appear. sum(n, acc=0) = n == 0 ? acc : sum(n-1, acc+1)
To me that negates much of the 'declarative' character of a functional style. I don't feel it's really clearer than the imperative for-loop acc = 0
for i = 1 to n
acc += 1 sum(0) = 0
when n != 0: sum(n) = n + sum(n-1)
is kind of clearer. But quite often it is not that easy to give an recursive solution for an iterative problem. When you want to change every even number in an array/list from n to n+1 you can somehow do it recursively, but it is mor obvious to iterate over the elements (which in many functional languages can be expressed by "apply" or some similar function).sum(1,n) = n*(n+1)/2
Which some compilers will produce for you, even if you use loops.
Maybe if you chose a different example, like generating power sets or the Fibonacci sequence, your point would be better made?
some people think in both. they should write blogs and help the whats and the hows communicate.