Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 5 1 21 123 4321 12345

C Code Example — Pattern Programs

ADVERTISEMENT

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

  1. Run an outer loop i from 1 to 5.
  2. Inside the loop, use an if (i % 2 == 0) condition to check if the current row is even.
  3. If even, run a loop from i down to 1, printing descending numbers.
  4. If odd, run a loop from 1 up to i, printing ascending numbers.
  5. 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)
ADVERTISEMENT