diff options
Diffstat (limited to 'challenge-003')
| -rw-r--r-- | challenge-003/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-003/abigail/c/ch-2.c | 69 |
2 files changed, 70 insertions, 0 deletions
diff --git a/challenge-003/abigail/README.md b/challenge-003/abigail/README.md index 3f6c33f85f..a8af310c3b 100644 --- a/challenge-003/abigail/README.md +++ b/challenge-003/abigail/README.md @@ -38,4 +38,5 @@ rows from the command line. The Pascal Triangle should have at least ### Solutions * [AWK](awk/ch-2.awk) +* [C](c/ch-2.c) * [Perl](perl/ch-2.pl) diff --git a/challenge-003/abigail/c/ch-2.c b/challenge-003/abigail/c/ch-2.c new file mode 100644 index 0000000000..32307ac156 --- /dev/null +++ b/challenge-003/abigail/c/ch-2.c @@ -0,0 +1,69 @@ +# include <stdlib.h> +# include <stdio.h> +# include <string.h> + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-1.o ch-1.c; ./ch-1.o < input-file + */ + +int main (void) { + char * line = NULL; + size_t len = 0; + size_t strlen; + + while ((strlen = getline (&line, &len, stdin)) != -1) { + int rows = atoi (line); + /* + * Declare two rows, and malloc memory for thew + */ + long long * row; + long long * new; + + if ((row = (long long *) malloc ((rows + 1) * sizeof (long long))) + == NULL) { + fprintf (stderr, "Out of memory\n"); + exit (1); + } + + if ((new = (long long *) malloc ((rows + 1) * sizeof (long long))) + == NULL) { + fprintf (stderr, "Out of memory\n"); + exit (1); + } + + /* + * 0th row + */ + row [0] = 1; + printf ("%lld\n", row [0]); + + for (int r = 1; r <= rows; r ++) { + /* + * Create the next row, and print it + */ + for (int i = 0; i <= r; i ++) { + new [i] = (i == 0 ? 0 : row [i - 1]) + + (i == r ? 0 : row [i]); + printf ("%s%lld", i == 0 ? "" : " ", new [i]); + } + printf ("\n"); + + /* + * Swap the two roles + */ + long long * tmp = new; + new = row; + row = tmp; + } + + free (new); + free (row); + } + free (line); + + return (0); +} |
