Skip to main content

Pattern N, eee, PPPPP using unformatted I/O

Short answer

Using only putchar, loop row from 1 to 5: print (5-row) pairs of spaces, then (2*row-1) copies of the letter from array {'N','e','P','a','L'} each followed by a space, and a newline. This produces the centered triangular pattern.

Write a program in C to generate following pattern using unformatted input/output functions only.

      N
    e e e
  P P P P P
 a a a a a a a
L L L L L L L L L

Only putchar() is used for output (unformatted), row r contains 2r - 1 copies of one letter, and each row is preceded by blanks to make a triangle.

#include <stdio.h>
int main(void)
{
    char letters[] = {'N', 'e', 'P', 'a', 'L'};
    int row, k;
    for (row = 1; row <= 5; row++)
    {
        for (k = 1; k <= 5 - row; k++)      /* leading blanks */
        {
            putchar(' ');
            putchar(' ');
        }
        for (k = 1; k <= 2 * row - 1; k++)  /* letter and a space */
        {
            putchar(letters[row - 1]);
            putchar(' ');
        }
        putchar('\n');
    }
    return 0;
}

Output:

        N 
      e e e 
    P P P P P 
  a a a a a a a 
L L L L L L L L L

Explanation

  • The outer loop runs once per row (5 rows) and picks the letter from the array.
  • The first inner loop prints 5 - row pairs of blanks, which shifts the row to the right.
  • The second inner loop prints 2*row - 1 letters, each followed by a blank.
  • The number of letters in the rows is 1, 3, 5, 7, 9.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 4 questions →