aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-01-28 02:15:48 +0100
committerAbigail <abigail@abigail.be>2021-01-28 02:22:08 +0100
commit9bbb334e1224120a789fecac7637a1cfc17c1b7d (patch)
treee3e76efa991f186021539e5ee8d282583969130c
parent94066ce3eb7bbfcf7da711e6e9f703df791a48de (diff)
downloadperlweeklychallenge-club-9bbb334e1224120a789fecac7637a1cfc17c1b7d.tar.gz
perlweeklychallenge-club-9bbb334e1224120a789fecac7637a1cfc17c1b7d.tar.bz2
perlweeklychallenge-club-9bbb334e1224120a789fecac7637a1cfc17c1b7d.zip
C solution for week 3, part 2
-rw-r--r--challenge-003/abigail/README.md1
-rw-r--r--challenge-003/abigail/c/ch-2.c69
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);
+}