K&R Exercise 1-20: tabs to spaces I'm learning C with K&amp;R 2nd Ed. I've just completed the exercise 1-20 and I would know if my code is correct (i.e. answering the question) and if my style is not too bad. Or just some feebacks to improve myself!


  K&amp;R Exercise 1-20 p.34
  
  Write a program detab that replaces tabs in the input with the proper number  * of blanks to space to the next tab stop.  Assume a fixed set of tab stops, say every n
  columns.  Should n be a variable or a symbolic parameter?


More info here

I put '-' because it's more readable than ' '. But you can totally change it.

#include &lt;stdio.h&gt;
#define COLUMN 8

int main()
{
    int c, i, nc;
    nc = 0;

    while ((c = getchar()) != EOF)
    {
        if (c != '\t' &amp;&amp; c != '\n')
            nc = (nc + 1) % COLUMN;

        if (c == '\n')
            nc = 0;

        if (c == '\t') {
            for (i=1; i&lt;=(COLUMN - nc); ++i) {
                putchar('-');
            }
            nc = 0;
        }
        else
            putchar(c);
    }

return(0);
}
Here is an alternate algorithm:

while ((c = getchar()) != EOF) {
    switch (c) {/* switch instead of if-else... */
    case '\n':
        nc = 0;
        putchar(c);
        break;
    case '\t':
        for (i = COLUMN - nc % COLUMN, nc += i; i &gt; 0; --i) {
            putchar('-');
        }
        break;
    default:
        ++nc; /* increment is faster than increment plus divide */
        putchar(c);
        break;
    }
}


nc keeps track of the current column position within the line.