打印2d阵列盒

时间:2016-10-24 08:33:27

标签: c

我是编程新手。想一想如何使用for循环打印出盒子,这样就可以制作一个大盒子?我附上了下面的样本。我真的需要帮助。

#include <stdio.h>

int main()
{     
 int a;

 printf("\n --- \n");
 for(a=1;a<=1;++a)
 printf("\n|   |\n");
 printf("\n --- ");

 return 0;
}

示例输出:

Example output

2 个答案:

答案 0 :(得分:0)

这样的事情可行。您需要对嵌套循环有基本的了解才能够解决这个问题。

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

int
main(int argc, char const *argv[]) {
    int rows, cols, i, j;

    printf("Enter rows for box: ");
    if (scanf("%d", &rows) != 1) {
        printf("Invalid rows\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter columns for box: ");
    if (scanf("%d", &cols) != 1) {
        printf("Invalid columns\n");
        exit(EXIT_FAILURE);
    }

    printf("\n2D Array Box:\n");
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= cols; j++) {
            printf(" --- ");
        }
        printf("\n");
        for (j = 1; j <= cols; j++) {
            printf("|   |");
        }
        printf("\n");
    }

    /* bottom "---" row */
    for (i = 1; i <= cols; i++) {
        printf(" --- ");
    }

    return 0;
}

答案 1 :(得分:0)

第一个字符(' ')和重复字符串("--- "
第一行和重复内容行和条形线。

#include <stdio.h>

#define MARK "X O"

//reduce code    
#define DRAW_H_BAR()\
    do {\
        putchar(' ');\
        for(int i = 0; i < cols; ++i)\
            printf("%s ", h_bar);\
        puts("");\
    }while(0)

void printBoard(int rows, int cols, int board[rows][cols]){
    const char *h_bar = "---";
    const char v_bar = '|';

    DRAW_H_BAR();//first line
    for(int j = 0; j < rows; ++j){
        //contents line
        putchar(v_bar);
        for(int i = 0; i < cols; ++i)
            printf(" %c %c", MARK[board[j][i]+1],v_bar);
        puts("");
        DRAW_H_BAR();//bar line
    }
}

int main(void){
    int board[8][8] = {
        {1,0,1,0,1,0,1,0},
        {0,1,0,1,0,1,0,1},
        {1,0,1,0,1,0,1,0},
        {0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0},
        {0,-1,0,-1,0,-1,0,-1},
        {-1,0,-1,0,-1,0,-1,0},
        {0,-1,0,-1,0,-1,0,-1}
    };
    int rows = sizeof(board)/sizeof(*board);
    int cols = sizeof(*board)/sizeof(**board);
    printBoard(rows, cols, board);
}