Interesting programming exercise- no loops

Recursive fractal
Image by Pete Linforth from Pixabay

I read about a university course where the students had to write C code without using For, While or Goto for loops. Instead they had to use recursion.

Yes it’s bound to be inefficient compared to the looping structure but that’s not the point. For instance for a loop like this:

for (int i=0;i<10;i++) {
   DoSomething(i);
}

It could be done as

void DoSomething(int i) {
   if (i==10) return;
  // Do whatever here
   DoSomething(i+1);
}

DoSomething(0);

The point isn’t to teach you to write inefficient code but to think a bit differently. I’ve used recursion quite extensively in the Slay tutorials code. Here’s an example. It sets a field continent in all adjacent land squares where continent == -1.

void FillIn(int x, int y, int island) {
	if (onMap(x, y)) {
		if (island == map[x][y].island && map[x][y].continent == -1) {
			map[x][y].continent = numContinents;
			allContinents[numContinents].count++;
			FillIn(x - 1, y, island);
			FillIn(x + 1, y, island);
			FillIn(x, y - 1, island);
			FillIn(x, y + 1, island);
			FillIn(x - 1, y - 1, island);
			FillIn(x + 1, y - 1, island);
			FillIn(x + 1, y + 1, island);
			FillIn(x - 1, y + 1, island);
		}
	}
}
(Visited 6 times, 1 visits today)