2016-10-24 12 views
-4

プログラミングに慣れていません。 forループを使用してボックスを印刷するにはどのようにすればよいのでしょうか?私は以下のサンプルを添付しました。私は本当に助けが必要です。2次元アレイボックスの印刷

#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

+0

私たちが表示したコードの問題は何ですか?そのプログラムの実際の出力は何ですか?どのようなアウトプットを期待しましたか?また、[良い質問をする方法について読む](http://stackoverflow.com/help/how-to-ask)をご覧ください。 –

+0

いくつかの宿題のように見えます。あなたは何をしたのかを示し、より具体的な質問を記述する必要があります。 –

+0

@プログラマーの間違って申し訳ありませんが、私が欲しいのは2次元の配列ボックスを '---'と '|'側面上。 – CodeX

答えて

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; 
} 
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); 
} 
関連する問題