C Program to Print Alphabet Pattern
for loops in C to print an alphabet pattern by incrementing a character variable inside the inner loop, for example: for(int i=0; i. Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n = 5; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { printf("%c", 'A' + j); } printf("\n"); } return 0; }
Dry Run
Let's trace the program for n=3 to see how it prints the pattern.
Start outer loop i=0
Inner loop j runs from 0 to 0, prints 'A' (65 + 0)
Print newline after row 0
Output so far: A
Outer loop i=1
Inner loop j runs 0 to 1, prints 'A' and 'B'
Print newline after row 1
Output so far: A AB
Outer loop i=2
Inner loop j runs 0 to 2, prints 'A', 'B', 'C'
Print newline after row 2
Output so far: A AB ABC
| Row (i) | Column (j) | Printed Character |
|---|---|---|
| 0 | 0 | A |
| 1 | 0 | A |
| 1 | 1 | B |
| 2 | 0 | A |
| 2 | 1 | B |
| 2 | 2 | C |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 0 to n-1, each iteration prints one row of the pattern.
Step 2: Inner loop prints letters
The inner for loop runs from 0 to the current row index, printing letters starting from 'A' by adding the loop index.
Step 3: Newline after each row
After printing letters for a row, printf("\n") moves the cursor to the next line for the next row.
Alternative Approaches
#include <stdio.h> int main() { int n = 5, i = 0; while (i < n) { int j = 0; while (j <= i) { printf("%c", 'A' + j); j++; } printf("\n"); i++; } return 0; }
#include <stdio.h> int main() { int n = 5; for (int i = 0; i < n; i++) { for (int j = i; j >= 0; j--) { printf("%c", 'A' + j); } printf("\n"); } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops run approximately n*(n+1)/2 times, which is O(n^2), because each row prints increasing letters.
Space Complexity
The program uses constant extra space, only variables for loop counters and no extra arrays.
Which Approach is Fastest?
All approaches use nested loops and have similar O(n^2) time; choice depends on readability and style preference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and clear pattern printing |
| While loops | O(n^2) | O(1) | Alternative loop style, same performance |
| Reverse pattern | O(n^2) | O(1) | Different pattern style, same complexity |