简体   繁体   English

在C中打印一个三角形

[英]Print a triangle in C

I want to develop a program which prints a triangle shown below: 我想开发一个打印三角形的程序,如下所示:

     1
    A B 
   1 2 3
  A B C D 

Using a for loop in C. Any idea how come up with program? 在C语言中使用for循环。您知道如何编写程序吗?

If you want to print n lines in total: 如果要总共打印n行:

  • the first line consists of 1 char and n-1 spaces in front of it 第一行包含1个字符和其前面的n-1空格
  • the second line consists of 3 chars and n-2 spaces in front of them 第二行包含3个字符和它们前面的n-2空格
  • the second line consists of 5 chars and n-3 spaces in front of them 第二行包含5个字符和它们前面的n-3空格
  • the i -th line consists of ___ chars and ___ spaces in front of them (please fill in missing fields i行由___字符和___前面的空格组成(请填写缺少的字段

How to determine what to print: 如何确定要打印的内容:

  • the first line consists of numbers 第一行由数字组成
  • the second line consists of alphabetical chars 第二行由字母字符组成
  • the third line consists of numbers 第三行由数字组成
  • the fourth line consists of alphabetical chars 第四行由字母字符组成

Please formulate a rule that determines which lines contain which signs: 请制定规则,确定哪些行包含哪些符号:

_______________________________________________________________________________

_______________________________________________________________________________  

You can print numbers with: printf("%d", number) . 您可以使用以下命令打印数字: printf("%d", number) You can print chars with printf("%c",char) . 您可以使用printf("%c",char)打印字符。

You can do addition on characters as well: 'A' + 2 yields 'C' . 您还可以对字符进行加法: 'A' + 2产生'C'

Now it should be no real problem to program the program you are looking for. 现在,对要寻找的程序进行编程应该不是真正的问题。

char * pie = "     1\n    A B\n   1 2 3\n  A B C D\n";
for (i=0;i<1;i++) printf("%s", pie);
f(int n)
{
  int i , j ;
  for( i = 1 ; i <= n ; i ++ )
  { 
    j = 1 ;
    while( j <= (n-i) ) { printf(" "); j++ ;}
    j = 0 ;
    while( j <= i )
    {
      if( i % 2 != 0 )
        printf("%d ", j );
      else
        printf("%c ", j + 'A' );
      printf("\n"); 
      j ++ ;
    }
  }
}

Now if someone can do it in time < O(n2) That is welcome :) 现在,如果有人可以及时做到这一点<O(n2)那就好了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM