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
429 views
in Technique[技术] by (71.8m points)

c - Printing a "triangle" of asterisks

The program I am supposed to write is supposed to print the triangle in the following manner:

If the number of rows is 2:

       *
      ***

If the number of rows is 3:

     *
    * *
   *****

However, the following code that I did prints the correct amount of stars for the last line, but I am not so sure how I would print the space and the newline. My code for printing the bottom level stars is the following:

  void tri_func(num)
{

     int row; int c=1;
     int j;

   for ( row = 1 ; row <= num ; row++ )
   {
      for (j=1; j < row-2; j++) printf(" ");
      for ( c = 1 ; c <= (2*row )- 1-j ; c++ )
      {
        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)

Well, if you have n lines, the first line should contain n-1 spaces and a *. The ith line (1< i < n) should contain n-i spaces, a *, 2i-3 spaces and another *, and the last line should contain 2n-1 *s. You can easily do it using loops. To print a space, use printf(" ");, and remember to print a in the end of every line.


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

...