about summary refs log tree commit diff
path: root/usth/ICT2.1/labwork/4/Ex3.c
diff options
context:
space:
mode:
Diffstat (limited to 'usth/ICT2.1/labwork/4/Ex3.c')
-rw-r--r--usth/ICT2.1/labwork/4/Ex3.c32
1 files changed, 32 insertions, 0 deletions
diff --git a/usth/ICT2.1/labwork/4/Ex3.c b/usth/ICT2.1/labwork/4/Ex3.c
new file mode 100644
index 0000000..ba016fc
--- /dev/null
+++ b/usth/ICT2.1/labwork/4/Ex3.c
@@ -0,0 +1,32 @@
+/*
+ * Read numbers from stdin to a link list and print their sum to stdout.
+ * This is free and unencumbered software released into the public domain.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "construct.h"
+
+construct *readoubles()
+{
+	double *x = malloc(sizeof(double));
+	if (scanf("%lf", x) != EOF)
+		return cons(x, readoubles());
+	free(x);
+	return NULL;
+}
+
+double sum(construct *list)
+{
+	if (list == NULL)
+		return 0.0;
+	/* At program termination the memory will be freed anyway. */
+	return *(double *) car(list) + sum(cdr(list));
+}
+
+int main()
+{
+	printf("%g\n", sum(readoubles()));
+	return 0;
+}