]> Pileus Git - ~andy/sfvlug/blob - c/src/loop.c
Add C notes.
[~andy/sfvlug] / c / src / loop.c
1 #include <stdio.h>
2
3 #define N_ELEM(x) (sizeof(x)/sizeof((x)[0]))
4
5 struct list {
6         const char *name;
7         struct list *next;
8 };
9
10 int main()
11 {
12         int i = 0;
13
14         /*
15          * While loops.
16          */
17         i = 0;
18         while (i < 3) {
19                 printf("Hello, %d!\n", i);
20                 i = i + 1;
21         }
22         printf("\n");
23
24         /*
25          * Do loops.
26          */
27         i = 0;
28         do {
29                 printf("Hello, %d!\n", i);
30                 i = i + 1;
31         } while (i < 3);
32         printf("\n");
33
34         /*
35          * For loops.
36          */
37         for (i = 0; i < 3; i++)
38                 printf("Hello, %d!\n", i);
39         printf("\n");
40
41         /*
42          * C99 only.
43          */
44         for (int j = 0; j < 3; j++)
45                 printf("Hello, %d!\n", j);
46         printf("\n");
47
48         /*
49          * Arrays
50          */
51         char *names[] = {"one", "two", "three"};
52         for (int i = 0; i < N_ELEM(names); i++)
53                 printf("Hello, %s!\n", names[i]);
54         printf("\n");
55
56         /*
57          * Linked lists.
58          */
59         struct list three = {"three"};
60         struct list two   = {"two", &three};
61         struct list one   = {"one", &two};
62         for (struct list *cur = &one; cur; cur = cur->next)
63                 printf("Hello, %s!\n", cur->name);
64         printf("\n");
65
66         return 0;
67 }