/*****************************************************************************\ * Exercise 8-1: a program that prints a grid from user-entered dimensions * * Author: Suzi Anvin * * Purpose: practice using for statements in C \*****************************************************************************/ #include int main() { char line[50]; int width = 0; /* user selected width of grid */ int height = 0; /* heigth of grid */ int i; /* counters */ int j; int k; int l; char noquit; /* y or n to restart program */ /* getting user dimensions for grid */ for (;;) { printf("Enter the size of desired grid A x B : "); fgets(line, sizeof(line), stdin); sscanf(line, "%d %*[^-0-9] %d", &width, &height); /* limiting grid size */ if (width > 12 || width <= 0 || height > 12 || height <= 0 ) { printf("Please enter positive values of 12 or smaller.\n"); continue; /* re-input dimensions */ } /* setting up the loop to draw a grid of the specified height, * avoiding the fencepost error by using height + 1 */ for (i = 0; i < (height + 1); i++) { /* setting up loops to draw a grid of the specified width. */ for (j = 0; j < width; j++) { /* print height + 1 vertical lines that are width long */ putchar('+'); for (k = 0; k < 5; k++) { putchar('-'); } } putchar('+'); putchar('\n'); /* setting up loop to draw the vertical sides */ if (i < height) { for (l = 0; l < 3; l++) { for (j = 0; j < width; j++) { putchar('|'); for (k = 0; k < 5; k++) { putchar(' '); } } putchar('|'); putchar('\n'); } } } printf("Would you like to print another grid? (y/n): "); fgets(line, sizeof(line), stdin); sscanf(line, "%c", &noquit); if (noquit == 'y') continue; else break; } return (0); }