The challenge for this month’s Exercise is to output a series of numbers, 1 through 10, and to ensure that the final number doesn’t look dorky. I’m certain that’s what I asked for.
Specifically, my point is to present a series like this:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
The goal is to ensure that a comma postfixes each of the other values, but not the last. Several solutions are possible. Here is the first one I came up with:
2025_05-Exercise-a.c
#include <stdio.h> int main() { int x; for( x=1; x<11; x++ ) { if( x<10 ) printf("%d, ",x); else printf("%d\n",x); } return 0; }
An if decision determines when the value of x
is less than 10. If so, the trailing comma and space are output. Otherwise, at the end of the list, only a new line is output after the final value.
One way to make this code more flexible is to set the looping value as a constant. So the for loop’s exit condition would be maxval
, which means the if statement uses maxval-1
as its test.
I stole the following code from the Interwebs, which does the same thing as my solution but in a more elegant and potentially cryptic manner:
2025_05-Exercise-b.c
/* from RosettaCode */
#include <stdio.h>
int main()
{
int x;
for( x=1; x<11; x++ )
{
printf("%d",x);
printf( x==10 ? "\n" : ", ");
}
return 0;
}
Here, the for loop’s second printf() statement contains the ternary operator, which sets the text to output after each value. The two printf() statements could be combined to make a single looping statement:
printf( (x==10 ? "%d\n" : "%d, "),x);
The ternary operator sets the printf() function’s format string, which is enclosed in parentheses. The presentation is wonderfully cryptic, plus it works.
In all cases, the proper solution is output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
No extra spaces are prefixed or suffixed to the output string, which makes it neat and tidy.
I’m certain other solutions are available, each of which must be delightful in some way. It’s this type of programming exercise that I find more engaging than some of the head-scratcher problems.