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:

  1. Initialize a number counter starting from 1.
  2. Determine the total number of rows (N).
  3. Loop through rows (from 1 to N).
  4. For odd-indexed rows, print numbers incrementing from the current number.
  5. For even-indexed rows, calculate the starting number based on the total numbers printed so far and print them in inverted order.
  6. Print the number followed by '*' except for the last number in the row.
  7. Increment the number after each print.
  8. Move to the next line after printing each row.

Method 1: Using Nested Loops

This method uses two loops to print the pattern.

#include <stdio.h>

int main() {
    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
                printf("%d", num++);  // Print the current number
                if (j < i) printf("*");  // 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
                printf("%d", start--);  // Print the current number in inverted order
                if (j < i) printf("*");  // Print '*' if not the last number in the row
            }
            num += i;  // Update num to the next starting number
        }
        printf("\n");  // Move to the next line after each row
    }

    return 0;
}
            

Output:

1
4*5*6
2*3
7*8*9*10