Numbers With Commas

As a programmer, you’re used to seeing values like 1000 or 1234999. Your users aren’t. They prefer to see values presented as 1,000 or 1,234,999.01. Or, in Europe the format may look like this 1.000 or 1.234.999,01.

The task for this exercise is to create a function that properly places the value separators inside a number string. You can choose whether to use US or European formats.

This is not an easy exercise. In fact, it’s darn difficult, especially if you’re just starting out in C. Regardless, I hope that you enjoy a challenge, especially if you have lots of time to work on this project.

Like most programming puzzles, this one can be best accomplished by breaking down the problem into chunks.

The first task is to obtain a value and convert it into a string. I would recommend generating a random value. Use the sprintf() function to convert the value into a string.

The second task is to work your way through the string to find the positions for the commas. One technique you can use is similar to an example I offer in my books: converting vowels in a sentence to some other character. But in this case, you’re not converting, you’re adding a character to the string. So review my vowel-conversion code and modify it so that the character (such as *) is inserted into the string.

The third task is to determine where the first comma is located. You could evaluate the string right-to-left, which is easy on your brain: Commas appear after every third digit. In C, however, strings are better dealt with left-to-right. So you need to determine where that first comma appears. As a big hint, that operation involves using the % operator on the string’s overall length.

The final task is to insert the commas after every third character. Again, the % operator is used. The technique you use to solve the second task could be employed to insert the commas into the string.

Here is sample output from my solution:

Before value:	1976768711
With commas:	1,976,768,711

As always, please attempt the exercise before you peek at my solution. Remember that my solution is merely one way to solve the problem.

Exercise Solution

Leave a Reply