Skip to content

C++:Example:NumberSquare

기본형

$ ./a.out 5 5
  1   2   3   4   5
  6   7   8   9  10
 11  12  13  14  15
 16  17  18  19  20
 21  22  23  24  25

코드는 다음과 같다:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s [options] {row} {col}\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int const row = atoi(argv[1]);
    if (row <= 0) {
        fprintf(stderr, "'row' must be an integer greater than 0.\n");
        exit(EXIT_FAILURE);
    }

    int const col = atoi(argv[2]);
    if (col <= 0) {
        fprintf(stderr, "'col' must be an integer greater than 0.\n");
        exit(EXIT_FAILURE);
    }

    int const size = row*col;
    for (int i = 1; i <= size; ++i) {
        printf("%3d ", i);
        if (0 == i%col) {
            putchar('\n');
        }
    }

    return 0;
}

See also