Viral Parmar
Viral Parmar

Reputation: 488

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?

Upvotes: 0

Views: 1855

Answers (3)

S..K
S..K

Reputation: 2024

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 :)

Upvotes: -1

steabert
steabert

Reputation: 6918

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);

Upvotes: 0

phimuemue
phimuemue

Reputation: 36071

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.

Upvotes: 4

Related Questions