user5544654
user5544654

Reputation:

Formatting for printf

I was given a problem where I was supposed to find factorals of numbers 1 - 20. That I completed, but in the example I was given the console if formatted to be visually appealing. Heres the example I was given. The white boxes were there because I was supposed to find the answers myself. So that can be ignored.

Correct Example

And here's what mine looks like.

My Example

We haven't been taught anything other than printf so I don't know any alternatives.

Here's my code.

long long lngFactoral = 1;
int intNumber = 1;

for (int intIndex = 1; intIndex <= 20; intIndex ++ )
{
    lngFactoral = lngFactoral * intIndex;
    printf("%d! = %lli ", intIndex, lngFactoral);

    intIndex++;

    lngFactoral = lngFactoral * intIndex;
    printf("                          %d! = %lli \n", intIndex, lngFactoral);
}

Upvotes: 0

Views: 519

Answers (1)

Pranav Chaudhary
Pranav Chaudhary

Reputation: 190

You can set field width in printf. You will have to specify the width with the format specifier using the integer value that sets the field width. For example, "%5d" or "%10d".

If the value to be printed is shorter than this number, the result is padded with blank spaces.

In your case your case you can modify your printf in the following manner:

First printf statement:

 printf("%2d! = %20lli ", intIndex, lngFactoral);

Second printf statement:

printf("   %2d! = %20lli \n", intIndex, lngFactoral);

%2d on the left-hand side is because you are finding the factorial of only 2 digit numbers, so we are going to set the field width 2.

Similarly,%20d is used on the right-hand side because the factorial of the largest number 20 is never going to exceed 20 digits.

Upvotes: 1

Related Questions