Formatting a Series for Output

Difficulty: ★ ★ ☆ ☆

Here is an issue that crops up often in programming, specifically when outputting data in a series: How do you separate items in the series and not make the last item look dorky? It’s tricky.

For example, consider the number sequence:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

The final value, 10, isn’t followed by a comma. This arrangement is how data is how humans (well, English-reading humans) read such a series. Commas separate the items. The final item lacks a comma and is instead followed by a period and a newline or just the newline (above).

Alternatively, you can eschew the commas and just follow each value with a space:

1 2 3 4 5 6 7 8 9 10 

The problem here is that the final value is also followed by a space, plus you must add in the newline.

A trick I use is to prefix the values with a space, which kinda solves the problem but not entirely:

 1 2 3 4 5 6 7 8 9 10

Therefore, a better and more rational solution should be available, which is the topic for this month’s Exercise.

Your challenge is to write a loop that outputs values 1 through 10. After the first nine values are output, add a comma and a space. The tenth value (10) is output followed by a newline.

This exercise may not seem very deep as far as C challenges go, but it does present multiple solutions. I found two. How many can you come up with?

Here’s a code skeleton to get you started:

2025_05_01-Lesson.c

#include <stdio.h>

int main()
{
    int x;

    for( x=1; x<11; x++ )
    {
        printf("%d, ",x);
    }

    return 0;
}

Click here to view my solutions.

3 thoughts on “Formatting a Series for Output

  1. This isn’t a 2 star problem 🙂 (Although I only wrote one solution.) Some people might prefer to split the “, ” or “\n” selection into a separate line.

    #include <stdio.h>

    int main()
    {
        int x;
        int max = 10;

        for(x=1; x<=max; x++)
        {
            printf(“%d%s”, x, x < max ? “, ” : “\n”);
        }

        return 0;
    }

  2. Hereʼs what I came up with:

    #include <stdio.h>

    int main (void)
    { static char const *sep [] = {"\n", ", "};
      int max = 10, x;

      for (x = 1; x <= max; ++x)
        printf ("%d%s", x, sep [x < max]);

      return (0);
    }

    If the requirements are weakened a bit so that there is no need for a space between the values, then the following would also work:

        printf ("%d%c", x, ('\n' + (','-'\n')*(x < max)));

    I am not sure if this really needs saying, but for anyone reading this: please donʼt do that… ever.

Leave a Reply