Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

c - How do I generate number pattern in triangular form

I want to print this pattern like right angled triangle

0   
909   
89098   
7890987    
678909876   
56789098765   
4567890987654   
345678909876543   
23456789098765432   
1234567890987654321 

I wrote the following code:


    #include <stdio.h>
    #include <conio.h>

    void main()
    {
        clrscr();
        int i,j,x,z,k,f=1;

        for ( i=10;i>=1;i--,f++)
        {
            for(j=1;j<=f;j++,k--)
            {
                k=i;

                if(k!=10)
                {
                    printf("%d",k);
                }

                if(k==10)
                {
                    printf("0");
                }

            }

            for(x=1;x<f;x++,z--)
            {
                z=9;
                printf("%d",z);
            }

            printf("%d/n");
        }

        getch();
    }

What is wrong with this code? When I check manually it seems correct but when compiled gives different pattern

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fairly simple: use two loops, one for counting up and one for counting down. Print literal "0" between the two.

#include <stdio.h>

int main()
{
    for (int i = 0; i < 10; i++) {
        for (int j = 10 - i; j < 10; j++)
            printf("%d", j);

        printf("0");

        for (int j = 9; j >= 10 - i; j--)
            printf("%d", j);

        printf("
");
    }

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...