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:
The string you are given is large enough to contain the largest integer (10 digits), including the negative sign and NUL terminator.void inttostr(int number, char string[]);
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:
For larger numbers, use modulo and division with larger powers of 10: 100, 1000, etc.42 / 10 ==> 4 42 % 10 ==> 2
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:
This is a partial inttostr.c with functions to get you started.gcc -O -Werror -Wall -Wextra -ansi -pedantic main.c inttostr.c -o inttostr
|
Output for all of the sample tests
Notes
strlen returns the length of the string, which is the number of characters in the string. It does not include the terminating NUL byte in the count. The type size_t is basically an unsigned integer type that you can use, if needed.size_t strlen(const char *string);
For those that would like an additional challenge:
"3.14159"