Print Character Pattern (Alphabet Matrix Pattern) in C
In this tutorial, we will develop a C program to print the following character pattern:
A B C D B C D E C D E F D E F G
Pattern Observation
Let’s analyze the pattern carefully:
- The pattern contains 4 rows and 4 columns.
- Each row starts from the next alphabet.
- Characters increase sequentially in each row.
| Row | Starting Character |
|---|---|
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
We can see that each character is generated using ASCII values. The formula used is:
'A' + i + j
C Program
#include <stdio.h>
int main() {
int i, j;
int n = 4; // Number of rows and columns
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("%c ", 'A' + i + j);
}
printf("\n");
}
return 0;
}
Explanation
1. Outer Loop (Rows)
The outer loop controls the rows (0 to 3).
2. Inner Loop (Columns)
The inner loop prints 4 characters in each row.
3. Character Logic
printf("%c ", 'A' + i + j);
- When i = 0 → prints A B C D
- When i = 1 → prints B C D E
- When i = 2 → prints C D E F
- When i = 3 → prints D E F G
This works because ASCII values of alphabets are consecutive.
Output
A B C D B C D E C D E F D E F G
Time Complexity
Two nested loops each run n times. Therefore, the time complexity is O(n²).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন