Develop a C program to draw a pattern of characters like the one shown below:
AB B
C C C
D D D D
Pattern Printing in C: Right-Aligned Alphabet Triangle
In this tutorial, we will develop a C program to print the following character pattern:
A
B B
C C C
D D D D
Problem Analysis
Observe the pattern carefully:
- Total rows = 4
- Number of characters increases in each row
- Spaces decrease in each row
- Each row prints the same alphabet repeatedly
| Row | Spaces | Characters Printed |
|---|---|---|
| 1 | 3 | A |
| 2 | 2 | B B |
| 3 | 1 | C C C |
| 4 | 0 | D D D D |
C Program
#include <stdio.h>
int main() {
int i, j;
int n = 4; // Total number of rows
for(i = 1; i <= n; i++) {
// Print leading spaces
for(j = 1; j <= n - i; j++) {
printf(" ");
}
// Print characters
for(j = 1; j <= i; j++) {
printf("%c ", 'A' + i - 1);
}
printf("\n");
}
return 0;
}
Explanation
1. Outer Loop (Rows)
The outer loop runs from 1 to 4 and controls the total number of rows.
2. First Inner Loop (Spaces)
This loop prints leading spaces before characters. The number of spaces is calculated as (n - i).
3. Second Inner Loop (Characters)
This loop prints characters equal to the row number.
4. Character Logic
The expression 'A' + i - 1 generates the required alphabet:
- i = 1 → A
- i = 2 → B
- i = 3 → C
- i = 4 → D
Output
A
B B
C C C
D D D D
Time Complexity
The outer loop runs n times and the inner loops also run up to n times. So the overall time complexity is O(n²).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন