The insane challenge for this month’s Exercise is to generate a countdown loop without using any looping functions. And, no, you can’t just use a buncha printf() statements to output the values.
If you’ve been reading this blog for any length of time, you probably know that when I use the word “insane” I’m referring to recursion. The inspiration for the exercise is based on the possibility of recursively calling the main() function.
I demonstrated a single recursive call to the main() function in a post from several years ago (Stupid main() Function Tricks). Upon reviewing that old post, I thought about taking the insanity a step further and using recursion in main() to output descending values. Here is the result, and my solution:
2025_04-Exercise.c
#include <stdio.h> int main(int argc, char *argv[]) { if( argc==11 ) return argc; printf("%d\n",main(argc+1,NULL)-1); return argc; }
The main() function calls itself within the printf() statement. Its arguments are the values of argc
(the argument count) plus one and NULL. The NULL is required and valid, but unusable. It doesn’t matter, however, as the countdown is what’s stored in argc
and what’s eventually output.
The trick is to get the values to output in reverse order. Therefore, the exit trigger for recursion is argc==11
— one more than ten. Once triggered, the value of argc
is returned and output in the printf() statement.
As recursion unwinds, each subsequent argc
value is output, 9 through 1. The final return argc
statement sends the last value, 1, to the operating system.
Here’s a sample run:
10
9
8
7
6
5
4
3
2
1
I hope that your solution also met with success. And if you came up with something different, I’d enjoy seeing it.