Problem Statement: Given an integer N, print the following pattern :

Here, N = 5.
Examples:
Input Format: N = 3 Result: A B C A B A Input Format: N = 6 Result: A B C D E F A B C D E A B C D A B C A B A
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Approach:
There are 4 general rules for solving a pattern-based question :
- We always use nested loops for printing the patterns. For the outer loop, we count the number of lines/rows and loop for them.
- Next, for the inner loop, we focus on the number of columns and somehow connect them to the rows by forming a logic such that for each row we get the required number of columns to be printed.
- We print the numbers inside the inner loop.
- Observe symmetry in the pattern or check if a pattern is a combination of two or more similar patterns or not.
This pattern problem is very similar to the last pattern problem we did where we had to print an increasing letter pyramid pattern but this time we have to print it in the reverse fashion. So, the outer loop will run for N rows and the inner loop will loop for N-i-1 alphabets in each row (where i is the row number) because the 1st row will have alphabets from A to A+(N-1). Alphabets in each row will start from A each time we enter a new row and will loop till (A+N-i-1)th alphabet in that row. In this way, the last row will only contain the alphabet A at last.
Code:
C++ Code
#include <bits/stdc++.h>
using namespace std;
void pattern15(int N)
{
// Outer loop for the number of rows.
for(int i=0;i<N;i++){
// Inner loop will loop for i times and
// print alphabets from A to A + (N-i-1).
for(char ch = 'A'; ch<='A'+(N-i-1);ch++){
cout<<ch<<" ";
}
// As soon as the letters for each iteration are printed, we move to the
// next row and give a line break otherwise all letters
// would get printed in 1 line.
cout<<endl;
}
}
int main()
{
// Here, we have taken the value of N as 5.
// We can also take input from the user.
int N = 5;
pattern15(N);
return 0;
}
Output
A B C D E
A B C D
A B C
A B
A
Java Code
class Main {
static void pattern15(int N)
{
// Outer loop for the number of rows.
for(int i=0;i<N;i++){
// Inner loop will loop for i times and
// print alphabets from A to A + (N-i-1).
for(char ch = 'A'; ch<='A'+(N-i-1);ch++){
System.out.print(ch + " ");
}
// As soon as the letters for each iteration are printed, we move to the
// next row and give a line break otherwise all letters
// would get printed in 1 line.
System.out.println();
}
}
public static void main(String[] args) {
// Here, we have taken the value of N as 5.
// We can also take input from the user.
int N = 5;
pattern15(N);
}
}
Output
A B C D E
A B C D
A B C
A B
A
Special thanks to Priyanshi Goel for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article. If you want to suggest any improvement/correction in this article please mail us at [email protected]