Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

loops - print empty asterisk triangle c

So I've looked up and only found normal triangles questions out there. This one is a bit tricky.

Given a N, your program should create an asterisk unfilled triangle with a N side size.

Example 1 
Inform N: 1 
*

Example 2:
Inform N: 2
**
*
Example 3:
Inform N: 3
***
**
*
Example 4:
Inform N: 4
****
* *
**
*
Example 5:
Inform N: 5
*****
*  *
* *
**
*

Here's my attempt, I could only make a filled triangle inefficiently

void q39(){
    int n,i,b;
    printf("Inform N: ");
    scanf ("%i",&n);
    for ( i = 0; i < n; ++i)
    {
    printf("*");
    for ( b = 1; b < n; ++b)
    {
        if (i==0)
        {
        printf("*");
        }
        else if (i==1 && b>1)
        {
            printf("*");
        }
        else if (i==2 && b>2)
        {
            printf("*");
        }
        else if(i==3 && b>3){
            printf("*");
        }
        else if(i==4 && b>4){
            printf("*");
        }
        else if(i==5 && b>5){
            printf("*");
        }
        else if(i==6 && b>6){
            printf("*");
        }
        else if(i==7 && b>7){
            printf("*");
        }
        else if (i==8 && b>8){
            printf("*");
        }
    }
        printf("
");
    }

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

you just need to think that first line should be filled with *.
Second thing is first character of every line should be *.
and last character should also be *. and in between you need to fill spaces.

int main()
{
    int n=6;
    for(int i=n-1;i>=0;i--) // using n-1, bcz loop is running upto 0
    {
        for(int j=0;j<=i;j++)
        {
            if(i==n-1 || j==0 ||i==j)
                printf("*");
            else
                printf(" ");
        }
        printf("
");      
    }
    return 0;
}

The condition if(i==n-1 || j==0 ||i==j)
here i==n-1 is used so that first line should be filled with *.
j==0 is used to make first character of every line *. every time when new line starts i.e j=0 it will print one * character.
i==j this is used to make last character * when i==j that is last index upto which we are running loop. so at last index it will print a *.
And for all other values it will print space as it will run else condition.

OUTPUT

******
*   *
*  *
* *
**
*

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...