#include using std::cout; using std::cin; using std::endl; int grid[25][25]; void drawLine(int x1, int y1, int x2, int y2) { // Draw pattern on bad input if ((x1 < 0 || x1 > 24) || (y1 < 0 || y1 > 24) || (x2 < 0 || x2 > 24) || (y2 < 0 || x2 > 24)) { drawLine(0,0,24,0); drawLine(0,24,24,24); drawLine(0,0,0,24); drawLine(24,0,24,24); drawLine(0,12,24,12); drawLine(12,0,12,24); return; } int rise = y2 - y1; int run = x2 - x1; grid[y1][x1] = 1; if (run > rise) { // slope less than 1 // step along x axis int y = y1; int p = y1; while (x1 != x2) { x1++; y += rise; if ( (p + run - y) < (y - p) ) { p += run; y1++; } grid[y1][x1] = 1; } } else { // slope greater than or equal to 1 // step along y axis int x = x1; int p = x1; while (y1 != y2) { y1++; x += run; if ( (p + rise - x) < (x - p) ) { p += rise; x1++; } grid[y1][x1] = 1; } } } void printGrid() { cout << "----------------------------------------------------" << endl; for (int i = 24; i >= 0 ; i--) { if (i < 10) cout << " "; // y axis cout << i; for (int j = 0; j < 25; j++) { if (grid[i][j]) { cout << "* "; } else { cout << " "; } } cout << endl; } cout << "----------------------------------------------------" << endl; cout << " 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2"<< endl; cout << " "; // x axis for (int i = 0; i < 25; i++) { cout << i % 10 << " "; } cout << endl << endl; } void clearGrid() { for (int i = 0; i < 25; i++) { for (int j = 0; j < 25; j++) { grid[i][j] = 0; } } } int main() { // Initialize grid clearGrid(); // Test lines // m <= 1 drawLine(0, 0, 24, 24); drawLine(0, 0, 24, 21); drawLine(0, 0, 24, 18); drawLine(0, 0, 24, 15); drawLine(0, 0, 24, 12); drawLine(0, 0, 24, 9); drawLine(0, 0, 24, 6); drawLine(0, 0, 24, 3); drawLine(0, 0, 24, 0); // m >= 1 drawLine(0, 0, 0, 24); drawLine(0, 0, 3, 24); drawLine(0, 0, 6, 24); drawLine(0, 0, 9, 24); drawLine(0, 0, 12, 24); drawLine(0, 0, 15, 24); drawLine(0, 0, 18, 24); drawLine(0, 0, 21, 24); drawLine(0, 0, 24, 24); printGrid(); // User-entered lines int x1; int y1; int x2; int y2; while (true) { cout << "Ctrl-c to quit" << endl; cout << "Each value should be between 0 and 24, inclusive, "; cout << "with x1 <= x2 and y1 <= y2" << endl; cout << "enter x1: "; cin >> x1; cout << "enter y1: "; cin >> y1; cout << "enter x2: "; cin >> x2; cout << "enter y2: "; cin >> y2; cout << x1 << " " << y1 << " " << x2 << " " << y2 << " " << endl; clearGrid(); drawLine(x1, y1, x2, y2); cout << "(x1, y1) = " << "(" << x1 << ", " << y1 << ") \n" << "(x2, y2) = " << "(" << x2 << ", " << y2 << ") " << endl; printGrid(); } return 0; }