K&R C Exercise 3-6: itoa with Minimum Field Width

Exercise 3-6. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.

This is exactly what printf‘s %6d format does — the 6 is a minimum field width that pads with spaces on the left. The implementation is a two-step process: first convert n to its digit string using the negative-domain technique from Exercise 3-4, then measure the result length and prepend the required number of spaces. Two important details: the sign character '-' counts toward the field width, and the width is a minimum — if the number is already wider than width, it is printed in full with no truncation.

Solution

/* K&R Exercise 3-6 — itoa with minimum field width
 * Compile: gcc -ansi -Wall ex3-6.c -o ex3-6 */
#include <stdio.h>
#include <string.h>

void reverse(char s[])
{
    int i, j;
    char c;
    for (i = 0, j = strlen(s)-1; i < j; ++i, --j) {
        c = s[i]; s[i] = s[j]; s[j] = c;
    }
}

void itoa(int n, char s[], int width)
{
    int i, sign, tlen, pad, j;
    char tmp[32];

    sign = n;
    i = 0;
    do {
        tmp[i++] = -(n % 10) + '0';
    } while ((n /= 10) < 0);
    if (sign < 0)
        tmp[i++] = '-';
    tmp[i] = '\0';
    reverse(tmp);

    tlen = strlen(tmp);
    pad = (width > tlen) ? width - tlen : 0;

    j = 0;
    while (pad-- > 0)
        s[j++] = ' ';
    for (i = 0; tmp[i] != '\0'; ++i)
        s[j++] = tmp[i];
    s[j] = '\0';
}

int main(void)
{
    char s[32];

    itoa(42,     s, 6);  printf("[%s]\n", s);  /* [    42] */
    itoa(-42,    s, 6);  printf("[%s]\n", s);  /* [   -42] */
    itoa(123456, s, 4);  printf("[%s]\n", s);  /* [123456] — no truncation */
    itoa(0,      s, 1);  printf("[%s]\n", s);  /* [0] */
    return 0;
}

The brackets in printf("[%s]\n", s) make the padding visible. Notice that -42 with width 6 produces three spaces then -42 — the minus sign takes one of the six positions.

Compile and Run

gcc -ansi -Wall ex3-6.c -o ex3-6
./ex3-6

Sample Output

[    42]
[   -42]
[123456]
[0]

What This Exercise Teaches

  • Field-width formatting — the same concept behind printf‘s %6d: a minimum width that pads left with spaces
  • Two-step build-then-pad — generate the number string first, measure it, then prepend spaces; avoids the complexity of counting in advance
  • Sign counts toward field width-42 is three characters wide; padding to width 6 adds three spaces, not four
  • Width is a floor, not a cap — numbers wider than width are printed in full; nothing is ever truncated

Set Up Your C Environment

← Exercise 3-5  | 
Chapter 3 Solutions  | 
Chapter 4 Solutions →

Book:
The C Programming Language, 2nd Ed — Kernighan & Ritchie

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>