the pyramid of numbers

Asked 2 years ago, Updated 2 years ago, 24 views

void main() { int i, j, num;

for(i=1; i<=5; i++)
{
    for (j = 1; j <= 5 - i; j++)
    {
        printf(" ");
    }
    for (num = 1; num <= 9; num++)
    {
        printf("%d", num);
    }
    printf("\n");
}

}

When I did it, 1 123 12345 1234567 123456789 I want to make pyramids in order. How do I fix it

c++

2022-09-20 11:01

1 Answers

I don't think you can solve the problem because you don't have a hint. I'll give you a hint.

It's a trick that's really easy when you get to know it, but it's hard to think of at first.

for (i = 1; i <= 9; i += 2) { /* something */ }

Required to film "123456789" on line 5.

for (j = 1; j <= (2 * 5) - 1; j++) { /* blah blah */}

For example, the third line should be marked with __12345__.
But by the time we start taking this line, we already know how many letters the line that has to take the most is taking the total number of letters.
That is, you know the width of this line.
It's 9.
However, line 3 only takes 5.
9-5=4, line 3 should have these 4 blanks half on the left and half on the right.
Huh? Is this a coincidence or a necessity?
If it's not a coincidence, isn't this kind of formula applicable to all lines as well as line 3?

Do it a little more!


2022-09-20 11:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.