]> Pileus Git - ~andy/sfvlug/blobdiff - c/src/loop.c
Add C notes.
[~andy/sfvlug] / c / src / loop.c
diff --git a/c/src/loop.c b/c/src/loop.c
new file mode 100644 (file)
index 0000000..814f653
--- /dev/null
@@ -0,0 +1,67 @@
+#include <stdio.h>
+
+#define N_ELEM(x) (sizeof(x)/sizeof((x)[0]))
+
+struct list {
+       const char *name;
+       struct list *next;
+};
+
+int main()
+{
+       int i = 0;
+
+       /*
+        * While loops.
+        */
+       i = 0;
+       while (i < 3) {
+               printf("Hello, %d!\n", i);
+               i = i + 1;
+       }
+       printf("\n");
+
+       /*
+        * Do loops.
+        */
+       i = 0;
+       do {
+               printf("Hello, %d!\n", i);
+               i = i + 1;
+       } while (i < 3);
+       printf("\n");
+
+       /*
+        * For loops.
+        */
+       for (i = 0; i < 3; i++)
+               printf("Hello, %d!\n", i);
+       printf("\n");
+
+       /*
+        * C99 only.
+        */
+       for (int j = 0; j < 3; j++)
+               printf("Hello, %d!\n", j);
+       printf("\n");
+
+       /*
+        * Arrays
+        */
+       char *names[] = {"one", "two", "three"};
+       for (int i = 0; i < N_ELEM(names); i++)
+               printf("Hello, %s!\n", names[i]);
+       printf("\n");
+
+       /*
+        * Linked lists.
+        */
+       struct list three = {"three"};
+       struct list two   = {"two", &three};
+       struct list one   = {"one", &two};
+       for (struct list *cur = &one; cur; cur = cur->next)
+               printf("Hello, %s!\n", cur->name);
+       printf("\n");
+
+       return 0;
+}