작은숲:위키노트/C 언어 예제/다이아몬드 출력 2

큰숲백과, 나무를 보지 말고 큰 숲을 보라.
/**
 * Copyright (c) 2001,2002 Yoon, Hyunho <hhyoon@kldp.org>
 * http://mooo.org
 * ----------------------------------------------------------------------
 *
 * LICENSE
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
/**
 * 빈칸과 별표를 이용해 다이아몬드 모양을 출력하는 프로그램 ..
 *
 * 라인의 수를 사용자에게 입력받아 그 라인 크기의 다이아몬드 모양을 ..
 * 출력한다.
 * 사용자에게 입력받은 라인의 수는 반드시 홀수가 되야 한다.
 * 그래야 제대로 된 다이아몬드 형태를 출력할 수 있다.
 * 짝수일 경우에는 다시 입력받는다.
 *
 * 각 라인에 따라 출력될 빈칸과 별표의 수를 결정해줘야 한다.
 * 빈칸과 별표의 개수를 변수에 저장시켜 이것을 for loop를 ..
 * 이용하여 화면에 출력한다.
 *
 * 빈칸과 별표의 수를 결정하는 것은 다이아몬드 모양의 위부분인지 ..
 * 아래부분인지에 따라 다르게 해줘야 한다.
 * 이는 if 문을 사용하여 구현하면 된다.
 */
#include <stdio.h>
int main()
{    int i, j;        /* for loop에서 사용될 인덱스 변수 */
    int lines = 23;    /* 라인의 개수 */
    int stars;        /* 각 라인에 따른 별표의 수 */
    int spaces;        /* 각 라인에 따른 빈칸의 수 */
    int half;        /* 다아이몬드의 가운데 */
    /* 사용자에게 라인 수를 입력받는다. */
    /* 만약 라인 수가 5보다 작거나, 짝수이면 다시 입력하도록 한다. */
    do {
        printf("Enter the number of lines (Odd number): ");
        scanf("%d", &lines);
    } while (lines < 5 || lines % 2 == 0);
    /**
     * 다이아몬드의 가운데를 찾는다.
     * 이 가운데를 기준으로 상하 대칭이기 때문에 ..
     * 이것을 결정하는 것이 상당히 중요하다.
     */
    half = lines / 2;
    /* 라인의 수만큼 for loop를 돈다. */
    for (i = 0; i < lines; i++) {
        /* 각 라인에 따라 별표의 개수와 빈칸의 개수를 결정한다. */
        /* 다이아몬드의 위부분 */
        if (i < half) {
            stars = i * 2 + 1;
            spaces = half - i;
        }
        /* 다이아몬드의 아래부분 */
        else {
            stars = (lines - i) * 2 - 1;
            spaces = i - half;
        }
        printf("%2d: ", i + 1);
        /* 빈칸을 출력한다. */
        for (j = 0; j < spaces; j++)
            printf(" ");
        /* 별표를 출력한다. */
        for (j = 0; j < stars; j++)
            printf("*");
        /* 라인의 끝나면 개행문자를 출력한다. */
        printf("\n");
    }
    return 0;
}
이 작은숲 문서의 출처는 위키노트의 위키노트/C 언어 예제/다이아몬드 출력 2 문서입니다.