#include #include #include /* for strcmp */ #define LIFE_YMAX 10 #define LIFE_XMAX 10 int main() { int old[LIFE_YMAX + 2][LIFE_XMAX + 2] = { /* sorry y before x */ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /* a glider */ {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; int new[LIFE_YMAX + 2][LIFE_XMAX + 2]; int generation; char buffer[256]; size_t x, y; /* loop through all elements in the array */ int count; size_t x1, y1; /* subscript of each of the 8 neighbors of x, y */ for (generation = 0;; ++generation) { /* Print the matrix. */ for (y = 1; y <= LIFE_YMAX; ++y) { for (x = 1; x <= LIFE_XMAX; ++x) { /* sorry y before x */ putchar(old[y][x] ? 'X' : '.'); } putchar('\n'); } printf("%d: Press c to continue, q to quit, and RETURN.\n", generation); scanf("%s", buffer); if (strcmp(buffer, "c") != 0) { break; } for (y = 1; y <= LIFE_YMAX; ++y) { for (x = 1; x <= LIFE_XMAX; ++x) { /* How many of the 8 neighbors of element x, y are turned on? Don't count the element itself.*/ count = -old[y][x]; for (y1 = y - 1; y1 <= y + 1; ++y1) { for (x1 = x - 1; x1 <= x + 1; ++x1) { count += old[y1][x1]; } } /* Law of Survival */ if (count == 2) { new[y][x] = old[y][x]; } /* Law of Birth */ else if (count == 3) { new[y][x] = 1; } /* Law of Death */ else { new[y][x] = 0; } } } /* Copy new into old. */ for (y = 1; y <= LIFE_YMAX; ++y) { for (x = 1; x <= LIFE_XMAX; ++x) { old[y][x] = new[y][x]; } } } return EXIT_SUCCESS; }