Skip to content

Instantly share code, notes, and snippets.

@neuro-sys
Created March 10, 2014 08:10
Show Gist options
  • Save neuro-sys/9461191 to your computer and use it in GitHub Desktop.
Save neuro-sys/9461191 to your computer and use it in GitHub Desktop.
"Translating a simple iterative loop into a recursive version is about the quickest possible way of filtering out the non-programmers - even a rather inexperienced programmer can usually do it in 15 minutes, and it's a very language-agnostic problem, so the candidate can pick a language of their choice instead of stumbling over idiosyncracies."
#include <stdio.h>
/*
http://programmers.stackexchange.com/questions/182314/recursion-or-while-loops/182334#182334
Translating a simple iterative loop into
a recursive version is about the quickest possible
way of filtering out the non-programmers -
even a rather inexperienced programmer can
usually do it in 15 minutes,
*/
int sum_iterative(int n)
{
int i;
int sum = 0;
for (i = 0; i < n; i++) {
sum += i;
}
return sum;
}
int sum_recursive(int n)
{
if (n == 0)
return n;
return n + sum_recursive(--n);
}
int main(int argc, char *argv[])
{
printf("%d\n", sum_iterative(20));
printf("%d\n", sum_recursive(20));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment