2

This function prints every number starting from 0000 to 1000.

#include <stdio.h>

int main() {
    int i = 0;
    while ( i <= 1000 ) {
        printf( "%04d\n", i);
        i = i + 1; 
    }
    return 0;
}

The output looks like this:

0000
0001
0002
etc..

How can I make this more presentable using three different columns (perhaps using \t ) to have the output look like this:

0000 0001 0002
0003 0004 0005
etc..

1
  • Maybe make a string out of each line and then print that? Commented Aug 31, 2010 at 1:16

4 Answers 4

5

This is how I'd do it, to eliminate the potentially expensive if/?: statement:

char nl[3] = {' ', ' ', '\n'};
while ( i <= 1000 ) {
   printf("%04d%c", i, nl[i%3]);
   ++i; 
}

Note that the modulo division may be much more expensive than the branching anyhow, but this depends on your architecture.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I'm thinking...;)
I would do i % (sizeof(nl)/sizeof(*nl)) so that you only have to change one line if you want to change the number of columns.
3

To get 3 columns you need to print new line character only after each 3 numbers (in your case after a number if its remainder when divided by 3 is 2):

The simplest approach:

while ( i <= 1000 ) {
    if (i%3 == 2)
       printf( "%04d\n", i);
    else
       printf( "%04d ", i);
    i = i + 1; 
}

Or as pointed in comment you can make it shorter using ternary operator:

while ( i <= 1000 ) {
   printf("%04d%c", i, i%3==2 ? '\n' : ' ');
   ++i; 
}

1 Comment

Simpler is printf("%04d%c", i, i%3==2 ? '\n' : ' ');
1
while ( i <= 1000 )
{
   printf( i%3?"%04d ":"%04d\n", i );
   ++i;
}

should also works.

Comments

0

The only way I got it to work perfectly in terminal (console) was literally padding the string with a loop. The nice part is that you can choose which char to pad it with, like "Text .......... 234". Without manual padding most lines got aligned by printf, but a few remained little out of alignment.

  # This gets available cols in terminal window:
  w_cols=`tput cols`

  col2=15
  let "col1=($w_cols - $col2)"

  small="Hey just this?"
  bigone="Calm down, this text will be printed nicelly"     
  padchar='.'

  let "diff=${#bigone} - ${#small}"

  for ((i=0; i<$diff; i++)); 
    do
       small="${small}$pad_char"
    done

 # The '-' in '%-80s' below makes the first column left aligned.
 # Default is right all columns:

  printf "%-${col1}s\t%${col2}d\n"  "$small"  123456
  printf "%-${col1}s\t%${col2}d\n"  "$bigone"  123

The result is something like

  Hey just this?.....................................   123456
  Calm down, this text will be printed nicelly ......      123

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.