Practice Assignment

(inttostr.c)

Information

Before writing any code, you should write down the steps (in English or your native language) you need to take to solve these problems. This is your pseudocode. Once you have your pseudocode written, you can convert it into C code. If you can't write down the steps in English, you certainly can't write it in C.

The function you'll be writing for this practice deals with NUL-terminated C-style strings. The only header file you can include is string.h, and you'll only need the strlen function.


The function you will write converts an integer into a string. The name of the function is inttostr (integer to string) and the prototype is:

void inttostr(int number, char string[]);
The string you are given is large enough to contain the largest integer (10 digits), including the negative sign and NUL terminator.

Hint: Work on the positive numbers first before trying to deal with the negative numbers. You will use the mod operator, %, and the division operator, /, in a loop to extract the digits from the integer. (You've already seen this in other practices.) For example, to extract the two digits from the integer 42:

42 / 10 ==> 4
42 % 10 ==> 2
For larger numbers, use modulo and division with larger powers of 10: 100, 1000, etc.

Once you have the digit, convert it to a character (e.g. 4 + '0' == '4') and put the character in the proper position in the string. Consult an ASCII table to see why this works.

You may find it easier to build the string backwards (in reverse), and when you've finished building the string, just reverse it in place.

Approximate number of lines of code: 15.


Files:

The function goes in a C file named inttostr.c. The command line to build the program is:

gcc -O -Werror -Wall -Wextra -ansi -pedantic main.c inttostr.c -o inttostr
This is a partial inttostr.c with functions to get you started.
#include <string.h> /* strlen */

void inttostr(int number, char string[])
{

}
Here is main.c:   HTML    Text

Output for all of the sample tests

Notes

For those that would like an additional challenge:

  1. Write a function called floattostr converts a floating point number into a string. For example, the float value 3.14159 will be converted to this string:
    "3.14159"