13 October

Lining up columns using printf

Something we didn’t get to, that will help you print neat tables on assignment 7. We saw already that you can control the precision of a float value using %.2f for two digits after the decimal point.

You can also control the “width” of the field into which you are printing numbers, by putting a number before the decimal point: %10.2f means to print two digits after the decimal, but right-align the whole thing in a field of width 10. Here’s an example

    printf("%10.2f\n", 965.831);
printf("%10.2f\n", 0.1);
printf("%10.2f\n", 12345.0);

The output would be:

    965.83
      0.10
  12345.00

See how the right edge and the decimal points line up? If we use the * character to represent a space, then you can count that, including spaces, digits, and decimal point, there are exactly 10 characters on each line.

****965.83
******0.10
**12345.00

So if you want two columns to line up nicely, you could do:

    printf(" ------------- -------------\n");
    printf(" %12.1f  %12.1f\n", 14.6, 6.6);

to get:

 ------------- -------------
         14.6           6.6

For loops

An alternate syntax, where all the parts are at the top, usually on one line:

    for(int i = 0; i < 6; i++)
{
//BODY
}

This is roughly equivalent to

    int i = 0;
while(i < 6)
{
//BODY
i++;
}

Nested loops to print triangles

#include <stdio.h>
int main()
{
int i = 0; const int size = 8;
while (i < size)
{
// inner loop 1: print spaces
int j =1;
while(j<=i)
{
printf(" ");
j++;
}
// inner loop 2: print stars
int k=0;
while(k < size-i)
{
printf("*");
k++;
}
printf("\n");
i++;
}
return 0;
}

©2011 Christopher League · some rights reserved · CC by-sa