Incrementing + Inverted Squared Number-Star (Alternate Type 2)
Understanding the Problem
The goal is to print an alternate inverted squared number-star pattern where row order alternates, but follows a different sequence.
Pattern Explanation
The pattern follows a grid structure where numbers increase sequentially, but certain rows are printed in reverse order.
1*2*3*4
9*10*11*12
13*14*15*16
5*6*7*8
Observations:
- The pattern consists of 4 rows and 4 columns.
- Numbers increment from left to right across the grid.
- Each number is followed by a '*', except the last number in each row.
- Certain rows are printed in reverse order.
Algorithm
The pattern follows these steps:
- Initialize a number counter starting from 1.
- Store values in a 2D array as they increment.
- Loop through rows, printing normally for some rows and in reverse for others.
- Within each row, print numbers left to right with '*'.
- Move to the next line after printing each row.
Method 1: Using Nested Loops
This method first stores values in an array and then prints them in the required alternating order.
#include <stdio.h>
void printPattern(int n) {
int arr[n][n], num = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = num++;
}
}
for (int i = 0; i < n; i++) {
if (i == 1 || i == 3) {
for (int j = 0; j < n; j++) {
printf("%d", arr[i][j]);
if (j < n - 1) printf("*");
}
} else {
for (int j = n - 1; j >= 0; j--) {
printf("%d", arr[i][j]);
if (j > 0) printf("*");
}
}
printf("\n");
}
}
int main() {
int size = 4;
printPattern(size);
return 0;
}
Output:
1*2*3*4
9*10*11*12
13*14*15*16
5*6*7*8