본문 바로가기

공부/컴퓨터

[공학 프로그래밍] 달팽이 모양으로 배열에 숫자 채우기.

반응형

^_^

문제 : 달팽이 모양의 배열을 for 문을 이용하여 만들어라.

Source Code :
#include <stdio.h>

#define LEFT 0
#define DOWN 1
#define RIGHT 2
#define UP 3

main()
{
        int i;
        int t1,t2,t3,t4;
        int direct, value;
        int start_col, start_row;
        int array[5][5];
        
        i = 5;
        direct = RIGHT;

        start_col = 0; start_row = 0;
        value = 1;

        for ( t1 = 0 ; t1 < (i/2)+1 ; t1 ++ ) {
                // 바깥쪽을 채움
                // 채우기 시작하는 자리는 start_col,start_row 부터
                // 오른쪽, 아래, 왼쪽, 위쫏, 을 각각 채우고.
                // i/2+1 번 만큼 반복한다.
                if ( direct == RIGHT ) {
                        for ( t3 = start_col ; t3 < i-start_col ; t3 ++ ) {
                                array[t1][t3] = value;  value++;
                        }
                        direct = DOWN;
                        t3--;
                }
                if ( direct == DOWN ) {
                        for ( t4 = start_row+1  ; t4 < i-start_row ; t4++ ) {
                                array[t4][t3] = value;  value++;
                        }
                        direct = LEFT;
                        t4--;
                }
                if ( direct == LEFT ) {
                        for ( t3 = i-start_col-2  ; t3 >= start_col ; t3-- ) {
                                array[t4][t3] = value;  value++;
                        }
                        direct = UP;
                        t3++;
                }
                if ( direct == UP ) {
                        for ( t4 = i-start_row-2 ; t4 > start_row ; t4 -- ) {
                                array[t4][t3] = value;  value++;
                        }
                        direct = RIGHT;
                }
                // 채우기 시작할 자리를 x,y 각각 ++ 시켜준다.
                start_col++;
                start_row++;
        }

        for ( t1 = 0 ; t1 < 5 ; t1 ++ ) {
                for ( t2 = 0 ; t2 < 5 ; t2 ++ ) {
                        printf ("%3d", array[t1][t2]);
                }
                printf("
");
        }
}



반응형