Skip to main content

Pyramid pattern output program

Short answer

Use nested loops: for i=1 to 4, print (4-i) spaces and then characters 'A' through 'A'+i-1. This produces a right-aligned triangle: three spaces then A, two spaces then AB, one space then ABC, and ABCD.

Write a program to display the output in pyramid form as follows:

   A
  AB
 ABC
ABCD

Each line i (1 to 4) needs (4 − i) leading spaces followed by the first i letters starting from 'A'.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int rows = 4;
    for (int i = 1; i <= rows; i++) {
        for (int s = 1; s <= rows - i; s++)   // leading spaces
            cout << ' ';
        for (int j = 0; j < i; j++)           // letters A, B, C ...
            cout << char('A' + j);
        cout << endl;
    }
    return 0;
}

Output

   A
  AB
 ABC
ABCD

Alternative using manipulators: build the string str of letters for each line and print cout << setw(rows) << str << endl;, which right-aligns it in a field of width 4.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →