Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - Printing 2d array box

I am new to programming. Figuring on how can I print out the box using for loop so it makes a big box? I had attached the sample below. I really need help.

#include <stdio.h>

int main()
{     
 int a;

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

 return 0;
}

Example output:

Example output

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this could work. You need basic understanding of nested loops to be able to do this question.

#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
");
        exit(EXIT_FAILURE);
    }

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

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

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

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...