MCS 275 midterm #2 19971024 D. J. Bernstein

Your answers must be based solely on your own knowledge and the information on this sheet. You may keep this sheet; anything that you want to have graded must appear in the answer booklet. Note that this sheet has two sides.

Problem 1. Write a function strcspn that works as follows. strcspn has two string arguments, source and find. It starts at the beginning of source, searches through source for a character contained in find, and returns the position of that character (i.e., the number of characters before it in source).

For example, strcspn("HELLO","ABCDE") returns 1; strcspn("HELLO","L")
returns 2; strcspn("HELLO","GF") returns 5.

Problem 2. A program contains two files: foo.c and main.c. foo.c contains

      int a;
      static int b;
      extern int c;
      int d;
      int foo()
      {
        a = 1;
        b = 2;
        c = 3;
        d = 4;
      }

and main.c contains

      static int a;
      static int b;
      int c;
      extern int d;
      int main()
      {
        a = 5;
        b = 6;
        c = 7;
        d = 8;
        foo();
        printf("%d %d %d %d\n",a,b,c,d);
        return 0;
      }

What does this program print?

Problem 3. Write an echo program that prints its command-line arguments, not including the echo name. Put a space after each argument. Exception: Put a newline after the last argument. For example, echo hi there should print hi, a space, there, and a newline.

Problem 4. Explain what this program does.

      #include <stdio.h>
      char x[100];
      int xlen = 0;
      int main()
      {
        int c;
        int i;
        while ((c = getchar()) != EOF) {
          if (c == '\n') {
            i = xlen;
            while (i) putchar(x[--i]);
            putchar(c);
            xlen = 0;
          }
          else
            x[xlen++] = c;
        }
      }

Extra credit. Write a function printhex(n) that prints the integer n in hexadecimal. For example, printhex(300) should print the string 12c.