- 2068 Baisakh · 6 marks
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)
Related questions
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- Write and display 10 employees using file · Object Oriented Programming, chapter 8
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Pattern: PULCHOWK using unformatted output · Computer Programming, chapter 4
- SOP/POS forms and canonical form of A+BC+ABC · Digital Logic, chapter 3
- Suspension bridge triangle ABC; span AB · Surveying I, chapter 7
- Output of arithmetic expression program · Computer Programming, chapter 3