C Program to print Pattern 5 1 21 123 4321 12345
Objective
Write a C program to print an alternating direction number triangle.
Algorithm / Approach
- Run an outer loop
ifrom 1 to 5. - Inside the loop, use an
if (i % 2 == 0)condition to check if the current row is even. - If even, run a loop from
idown to 1, printing descending numbers. - If odd, run a loop from 1 up to
i, printing ascending numbers. - Print a newline.
main.c
#include<stdio.h>
int main( ) {
int i,j;
for(i=1;i<=5;i++) {
if(i%2==0) {
for(j=i;j>=1;j--) {
printf("%d",j);
}
}
else {
for(j=1;j<=i;j++) {
printf("%d",j);
}
}
printf("\n");
}
return 0;
}
Expected Output
1 21 123 4321 12345
Explanation of the Program
- This pattern introduces conditional logic inside the loop.
- Odd rows (1, 3, 5) count upwards (1, 123, 12345). Even rows (2, 4) count downwards (21, 4321). By using the modulo operator to determine the row parity, we can execute completely different inner loops for different rows.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)