Pattern:
ABCD
123
AB
1
Solution
Note: Don't jump directly to the solution, try it out yourself first.
Approach:
1)Require minimum 2 nested loop
2)Outer loop is for row
3)Inner loop is for column
4)Print in inner loop
Pattern Breakdown
The pattern has 4 rows, and each row contains stars (*) in a decreasing number:
Row 0: 4 characters (****) 0 Space
Row 1: 3 Digit(***) 1 Space
Row 2: 2 characters(**) 2 Spaces
Row 3: 1 Digit(*) 3 Spaces
To print this pattern, we need two loops:
Outer loop for the rows.
Inner loop for the columns (printing spaces and characters in each row).
In each iteration of the outer loop:
The inner loop first prints spaces, and in second inner loop prints the respective character for the row.
The number of spaces in each row is equal to the row index (row).
The number of characters in each row is total_rows - row.
The characters alternate between letters (starting with 'A'), and digits (starting with '1').
Video
Java |
public class Main {
public static void main(String[] args) {
int total_rows = 4; // Number of rows
// Outer loop for rows
for (int row = 0; row < total_rows; row++) {
char current_char = 'A'; // Reinitialize current_char for each row
// Inner loop for spaces
for (int space = 0; space < row; space++) {
System.out.print(" ");
}
// Inner loop for characters
for (int col = 0; col < total_rows - row; col++) {
if (row % 2 == 0) {
System.out.print(current_char); // Print alphabetic characters on even rows
current_char++; // Move to the next letter for even rows
} else {
System.out.print(col + 1); // Print numeric characters on odd rows
}
}
System.out.println(); // Move to the next line
}
}
}
|
C++ |
#include <iostream>
using namespace std;
int main() {
int total_rows = 4; // Number of rows
// Outer loop for rows
for (int row = 0; row < total_rows; row++) {
char current_char = 'A'; // Reinitialize current_char for each row
// Inner loop for spaces
for (int space = 0; space < row; space++) {
cout << " ";
}
// Inner loop for characters
for (int col = 0; col < total_rows - row; col++) {
if (row % 2 == 0) {
cout << current_char; // Print alphabetic characters on even rows
current_char++; // Move to the next letter for even rows
} else {
cout << col + 1; // Print numeric characters on odd rows
}
}
cout << endl; // Move to the next line
}
return 0;
}
|
Python |
total_rows = 4 # Number of rows
# Outer loop for rows
for row in range(total_rows):
current_char = 'A' # Reinitialize current_char for each row
# Inner loop for spaces
for space in range(row):
print(" ", end="")
# Inner loop for characters
for col in range(total_rows - row):
if row % 2 == 0:
print(current_char, end="") # Print alphabetic characters on even rows
current_char = chr(ord(current_char) + 1) # Move to the next letter for even rows
else:
print(col + 1, end="") # Print numeric characters on odd rows
print() # Move to the next line
|