Print symmetric double triangle pattern in C language

Given with number of lines the program must print the symmetric double triangle pattern with least complexity.

Example

Input: 5
Output:  X
          X
          O X
           O X
      X O X O X
       X O
        X O
         X
          X


The entire problem contains 3 different partitions −

  • Print upper half with n-1 lines for odd n or n-2 lines for even n.

  • Print middle lines, 1 line for odd n or 3 lines for even n.

  • Print lower half, with n-1 lines for odd n or n-2 lines for even n

Algorithm

START
   STEP 1: IF (n % 2 == 0) then
      x = x - 1;
      Define p as n – 1 for spaces
      Define s = 1 for characters
   STEP 2: LOOP FOR i= 1 AND i 

Example

#include 
// printing alternate x o starting with x
int printx(int n) {
   int i;
   for ( i = 1; i ");
         p++;
      for ( j = 1; j ");
         p--;
         s++;
   }
   // extra upper middle for even
   if (n % 2 == 0) {
      for ( i = 1; i ");
   }
   // middle line
   if (n % 2! = 0)
      printx(n);
   else {
      if (n % 4! = 0) {
         printx(n / 2);
         printx(n / 2);
      } else {
         printx(n / 2);
         printo(n / 2);
      }
   }
   printf("
");    // extra lower middle for even    if (n % 2 == 0) {       printf(" ");       printx(n / 2);       printf("
");    }    // lower half    p = 1;    if (n % 2 == 0) {       x--;       p = 2;    }    int q = x / 2;    // one line for each iteration    for ( i = 1; i ");          p++;    }    printf("
");    return 1; } int main() {    int n = 5;    printpattern(n);    return 0; }

Output

If we run above program then it will generate following output.

      X
       X
       O X
        O X
   X O X O X
    X O
     X O
      X
       X
Updated on: 2019-08-22T09:42:30+05:30

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements