Incrementing Triangle Pattern + Inverted (Mix)
Understanding the Problem
The goal is to print a mixed triangle pattern where some rows are incrementing and others are inverted, with numbers incrementing sequentially.
Pattern Explanation
The pattern consists of alternating rows of incrementing and inverted incrementing sequences.
1 4*5*6 2*3 7*8*9*10
Observations:
- The pattern consists of 4 rows.
- Numbers increment from left to right.
- Odd-indexed rows (1st and 3rd) are incrementing, while even-indexed rows (2nd and 4th) are inverted.
- Each number is followed by a '*', except the last number in each row.
Algorithm
The pattern follows these steps:
- Initialize a number counter starting from 1.
- Determine the total number of rows (N).
- Loop through rows (from 1 to N).
- For odd-indexed rows, print numbers incrementing from the current number.
- For even-indexed rows, calculate the starting number based on the total numbers printed so far and print them in inverted order.
- Print the number followed by '*' except for the last number in the row.
- Increment the number after each print.
- Move to the next line after printing each row.
Method 1: Using Nested Loops
This method uses two loops to print the pattern.
public class IncrementingInvertedTrianglePattern { public static void main(String[] args) { int n = 4; // Number of rows int num = 1; // Starting number // Loop to print the mixed incrementing and inverted triangle pattern for (int i = 1; i <= n; i++) { // Loop for each row if (i % 2 != 0) { // Odd rows (1st and 3rd) for (int j = 1; j <= i; j++) { // Loop for each column in the current row System.out.print(num++); // Print the current number if (j < i) System.out.print("*"); // Print '*' if not the last number in the row } } else { // Even rows (2nd and 4th) int start = num + i - 1; // Calculate starting number for inverted row for (int j = 1; j <= i; j++) { // Loop for each column in the current row System.out.print(start--); // Print the current number in inverted order if (j < i) System.out.print("*"); // Print '*' if not the last number in the row } num += i; // Update num to the next starting number } System.out.println(); // Move to the next line after each row } } }
Output:
1 4*5*6 2*3 7*8*9*10