1

I'm doing a homework assignment in C where part of it involves printing the values with certain spacing between each integer. For example, using Pascal's Triangle:

  1 
  1 1 
  1 2  1 
  1 3  3  1 
  1 4  6  4   1 
  1 5 10 10   5   1 
  1 6 15 20  15   6  1 
  1 7 21 35  35  21  7  1 
  1 8 28 56  70  56 28  8 1 
  1 9 36 84 126 126 84 36 9 1 

The spacing between the integers in each column is exactly as wide as the largest integer +1. What's the best way to approach this?

ESM
  • 175
  • 10

1 Answers1

1

Dynamic spacing using printf can be achieved using the special character *.

A field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision.

Here is a basic testing program. You may want to use the special character -:

#include <stdio.h>

int main(void)
{
    int i;

    printf("Select your spacing: ");
    scanf("%d", &i);
    printf("Spacing is at least %d: |%*d|\n", i, i, 1);
    printf("Spacing is at least %d: |%-*d|\n", i, i, 1);
    return (0);
}

You still need to find the largest number from your problem and to process its width. This has to be done before you print anything. Good luck !

AugustinLopez
  • 348
  • 1
  • 3
  • 13