2016-10-24 2 views
-4

Ich bin neu in der Programmierung. Wie kann ich die Box mit for Schleife ausdrucken, so dass es eine große Box macht? Ich hatte das Beispiel unten beigefügt. Ich brauche wirklich Hilfe.Drucken 2d Array-Box

#include <stdio.h> 

int main() 
{  
int a; 

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

return 0; 
} 

Beispiel Ausgabe:

Example output

+0

Was ist Ihr Problem mit dem Code, den Sie uns zeigen? Was ist die tatsächliche Ausgabe dieses Programms? Welche Leistung haben Sie erwartet? Auch bitte [lesen Sie, wie man gute Fragen stellt] (http://stackoverflow.com/help/how-to-ask). –

+0

Sieht aus wie Hausaufgaben. Sie müssen zeigen, welche Anstrengungen Sie unternommen haben und Ihre Frage genauer beschreiben. –

+0

@some Programmierer dude sorry für ungenau, was ich will, ist eine 2d-Array-Box mit '---' oben und '|' auf der Seite. – CodeX

Antwort

0

So etwas wie dies funktionieren könnte. Sie benötigen ein grundlegendes Verständnis für verschachtelte Schleifen, um diese Frage beantworten zu können.

#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

erste Zeichen (' ') und Wiederholungs-String ("--- ")
erste Zeile und die Inhalte Leitung und Taktstrich wiederholen.

#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); 
}