INF2270 Oppgaver uke 6 (6.-11.2.2008) Oppgave 1 #include int main(void) { int x, d, rest; printf("Gi et antall: "); scanf("%d", &x); d = x/12; rest = x%12; printf("%d er %d dusin og %d.\n", x, d, rest); } Oppgave 2 #define STREQ(s1,s2) (strcmp((s1),(s2))==0) Oppgave 3 Det finnes mange l?sninger, blant annet x = MIN(a,b) + 1; x = 1 - MIN(a,4); Disse vil bli ekspandert til henholdsvis x = a #include int main(int argc, char *argv[]) { FILE *f; int nc = 0, nw = 0, nl = 0, /* Antall tegn, ord, linjer */ c, in_word = 0; if (argc != 2) { printf("Usage: wc file\n"); return 1; } f = fopen(argv[1],"r"); if (f == NULL) { printf("wc: %s: No such file or directory\n", argv[1]); return 2; } c = fgetc(f); while (c != EOF) { nc++; if (c == '\n') nl++; if (isspace(c)) in_word = 0; else { if (! in_word) nw++; in_word = 1; } c = fgetc(f); } fclose(f); printf("%8d%8d%8d %s\n", nl, nw, nc, argv[1]); return 0; } Oppgave 5 #include #include typedef struct line_struct { struct line_struct *next; char contents[201]; } line; line *read_all_lines (void) { line *first = NULL, *last = NULL, *cur; char cur_line[201]; while (gets(cur_line) != NULL) { cur = malloc(sizeof(line)); strcpy(cur->contents, cur_line); /* Insert this line last in the list: */ if (first == NULL) { first = cur; last = cur; } else { last->next = cur; last = cur; } last->next = NULL; } } void print_all_lines (line *lp) { while (lp) { printf("%s\n", lp->contents); lp = lp->next; } } int main (void) { line *data = read_all_lines(); print_all_lines(data); return 0; }