Print a triangle in C
I want to develop a program which 开发者_C百科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?
If you want to print n
lines in total:
- the first line consists of 1 char and
n-1
spaces in front of it - the second line consists of 3 chars and
n-2
spaces in front of them - the second line consists of 5 chars and
n-3
spaces in front of them - the
i
-th line consists of___
chars and___
spaces in front of them (please fill in missing fields
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)
. You can print chars with printf("%c",char)
.
You can do addition on characters as well: 'A' + 2
yields '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 :)
精彩评论