[Courses] C Programming For Absolute Beginners, Lesson 4: Getting Looped

Jacinta Richardson jarich at perltraining.com.au
Mon Mar 12 00:01:43 UTC 2012


On 07/03/12 07:12, Leslie wrote:
> Yay for Jacinta!  I wanted my columns to be aligned on the rightmost
> digit, not the leftmost, but I couldn't figure out how to use the
> conditionals (for adding an extra space before a one-digit number)
> within the 'for-loop'.  I had given up on that extra formatting goody
> until I read her helpful hint about the curly braces! Now my table looks
> better, and here's the code:

I'm glad I could help.

printf is smarter than you know yet, so here's a neat trick.  printf has been 
designed to allow you to give it extra formatting information, so instead of this:

>     if (a<  10){
>         printf ("\t\t %i\t\t",a);
>     }
>     else {
>         printf ("\t\t%i\t\t",a);
>     }

You can write:

     printf("\t\t%2i\t\t", a);

The 2 there, says format within two characters, which means you'll get an extra 
space, if your number is less than 10.  Likewise you could write:

     printf("%18i\t\t", a);

if you wanted to allow for very big numbers without messing up your formatting.  
For example if you were counting from 1 to 1000.

Because you now don't need the two if() statements, you can combine both of your 
prints into one:

     printf("\t\t%2i\t\t%2i\n", a, total);

Or to handle counting from 1 to 1000, you might write:

     printf("%18i %18t\n", a, total);

(although this shifts the right hand column over by one more space than the 
original, so you might instead choose to format the total in %17i instead).

By default, printf() aligns to the right. If you wanted it to align starting on 
the left you put a minus in front of the number:

     printf("%-18i", a);    # print the value for a padded to 18 characters 
wide, but start in left most field.
     printf("%18i, a);       # print the value for a padded to 18 characters 
wide, but start in right most field.

I hope this helps.

     J


More information about the Courses mailing list