Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 레이어가 다른 다이아몬드 패턴 프로그램

<시간/>

숫자가 주어지면 주어진 n개의 다른 레이어로 다이아몬드 패턴을 생성하고 표시하는 작업입니다.

예시

Input: n = 3

출력:

C 레이어가 다른 다이아몬드 패턴 프로그램

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. -

  • 행 수 입력
  • 그리고 이 패턴에는 ((2 * n) + 1)개의 행이 있습니다.
  • 0 – n의 공백 수는 (2 * (n – i))입니다.
  • n+1부터 끝까지 공백의 수는 ((i – n) * 2)

알고리즘

Start
Step 1-> declare a function to print a pattern
   void print_pattern(int n)
   declare variables as int i, j
   Loop For i = 1 i <= n * 2 i++
      Print space
   End
   Print \n
   Loop For i = 1 and i <= (n * 2) – 1 and i++
      IF i<n
      Loop For j = 1 and j <= (n - i) * 2 and j++
         Print space
      End
   End
   Else
      Loop For j = 1 and j <= (i % n) * 2 and j++
         Print space
      End
      IF i < n
      Loop For j = 0 and j <= i % n and j++
         Print j
      End
      Loop For j = (i % n)-1 and j > 0 and j--
         Print j
      End
         Print 0
      End
      Else IF i > n
         Loop For j = 0 and j <= n – (i – n) and j++
            Print j
         End
         Loop For j = (n – (i – n))-1 and j > 0 and j--
            Print j
         End
            Print 0
      End
      Else
         Loop For j = 0 and j <= n and j++
            Print j
         End
         Loop For j = n –1 and j > 0 and j--
            Print j
         End
            Print 0
         End
            Print \n
         End
         Loop For i=1 and i<=n*2 and i++
            Print space
         End
            Print 0
Step 2-> In main()
   Declare variable as int n=3
   Call function print_pattern(n)

예시

#include <stdio.h>
void print_pattern(int n) {
   // putting the space in line 1
   int i, j;
   for ( i = 1; i <= n * 2; i++)
      printf(" ");
      printf("0\n");
   // generating the middle pattern.
   for ( i = 1; i <= (n * 2) - 1; i++) {
      // printing the increasing pattern
      if (i < n) {
         for ( j = 1; j <= (n - i) * 2; j++)
         printf(" ");
      } else {
         for ( j = 1; j <= (i % n) * 2; j++)
         printf(" ");
      }
      if (i < n) {
         for ( j = 0; j <= i % n; j++)
            printf("%d ", j);
         for ( j = (i % n) - 1; j > 0; j--)
            printf("%d ", j);
            printf("0");
      }
      // printing the decreasing pattern
      else if (i > n) {
         for ( j = 0; j <= n - (i - n); j++)
            printf("%d ", j);
         for ( j = (n - (i - n)) - 1; j > 0; j--)
            printf("%d ", j);
            printf("0");
      } else {
         for ( j = 0; j <= n; j++)
            printf("%d ", j);
         for ( j = n - 1; j > 0; j--)
            printf("%d ", j);
            printf("0");
      }
      printf("\n");
   }
   // putting the space in last line
   for ( i = 1; i <= n * 2; i++)
      printf(" ");
      printf("0");
}
int main() {
   int n = 3;
   print_pattern(n);
   return 0;
}

출력

C 레이어가 다른 다이아몬드 패턴 프로그램