Sample questions for Midterm 2:

Note that some of the terms and problems in these sample questions will be covered in
chapters 6.9 (Recursion) and 6.11 (Analysis). 

Also see homeworks 5 onwards in both the noon and 3pm sections for
sample problems: link .
  
1. Define the following terms:

   iteration
   recursion
   pre-test loop, post-test loop
   structured data type
   simple data type
   infinite loop
   backtracking
   base case (for recursion)
   recursive case
   big O
   best case analysis
   average case analysis
   worst case analysis

2. Translate the following for loop into a do-while loop:

    for (I = 0, tot = 0, cnt = 0; I < N; I += 2) {
      tot += I;
      cnt++;
      printf("%.2f\n",(float) tot / cnt);
    }

3. Write a piece of code to produce the following output. You must use the
the statment: "printf("\n");" to output a newline and this statement must occur
exactly once in your program.

    *
     **
      ***
       ****
      ***
     **
    *

4. What is the output of the following piece of code:

    for (I = 0; I < 12; I++) {
      for (J = 4 - (I % 4); J > 0; J--)
	printf(" ");
      for (J = 0; J < (I % 4) + 1; J++)
	printf("X");
      printf("\n");
    }

5. Give a piece of code that will copy the characters from a text
    file file1.txt to a new file file2.txt.  Furthermore, when copying
    the characters, any lower case characters in file1.txt should be
    written as a corresponding upper case character in file2.txt (if
    the character 'a' is read from file1.txt, the character 'A' should
    be written to file2.txt).

6. How do the fgetc and ungetc functions work?  Indicate the arguments
   each takes and what values they return.  Also, give an example of
   how each function is used.

7. Give code for:

   Sequential search of an array

   Sequential search of a sorted array

   Binary search of a sorted array

   Selection sort

   Insertion sort

   Merge of two adjacent segments of an array

   Mergesort given a predefined merge routine

8. Write a function that takes an array of characters S of length N and
   returns 1 if that array contains a palindrome and 0 otherwise.  A palindrome
   is a sequence of characters that is the same written backwards.

9. Write a recursive solution to the previous problem.

10. Write a recursive function that sums up the squares of all the numbers
    from 1 to N (i.e., SumSqrs(N) returns 1^2 + 2^2 + 3^2 + ... + N^2).

11. Given a 2D character array A:
    0 1 2 3
  0 e e X X
  1 X e e e
  2 X e X X
  3 e e e X

  and the function Visit:

  void Visit(char A[][4], int r, int c) {
    if (A[r][c] == 'e') {
      A[r][c] = '.';
      printf("<%d,%d> ",r,c);
      if (r > 0) Visit(A,r-1,c); /* 1 */
      if (c > 0) Visit(A,r,c-1); /* 2 */
      if (r < 3) Visit(A,r+1,c); /* 3 */
      if (c < 3) Visit(A,r,c+1); /* 4 */
    }
  }


  the program will print:

  <0,0> <0,1> <1,1> <2,1> <3,1> <3,0> <3,2> <1,2> <1,3>

  if we call Visit(A,0,0)

  how could you reorder the statements labeled /* 1 */ to /* 4 */ to
  print:

  <1,1> <1,2> <1,3> <2,1> <3,1> <3,0> <3,2> <0,1> <0,0>

  if we call Visit(A,1,1)?

  How about:

  <1,1> <2,1> <3,1> <3,2> <3,0> <0,1> <0,0> <1,2> <1,3>

12. Give the Big-O notation (the growth-rate function) for each of the
    following formulas:

      2                 
     N  + 3N + 4NlogN + 5/N

             2     3    N
     5N + 25N  + 3N  + 4

       2         2
     3N logN + 5N  + NlogN + 2N

13. Give a situation where each of the sorts discussed in class (insertion,
    selection, and merge) is optimal.  You should include a discussion of the
    performance characteristics of the sorting algorithm that backs up your
    answer.

14. Write a function to sum up the odd numbers from 1 to N. You must write, and make use of,
    a second function, with prototype:
         int IsOddNumber(int Num);
    which returns 1 if Num is Odd and 0 if Num is even.
    
15. Chris is trying to write a loop with a variable I that takes on values from 0
    to BIG_DADDY-1, where:
#define    BIG_DADDY	3000000
    He wants to call the function:
       int CheckForSpecialValue(int i)
    for each value of I, and sum up all the values returned by CheckForSpecialValue.
    Write this function for Chris. Do not use arrays.

16. What is output by the following program code:
        int month, I;

        for (month=1; month <= 12; month++) {
                for (I=1; I <= month-1; I++) {
                        printf("%d ", I);
                }
                printf("\n");
        }

17. Add in the appropriate program code for opening the file "file.txt", including
    any necessary checking for errors or failure to open the file successfully.
    Give the content of the file "file.txt" afterwards assuming that the user
    types the three characters: ab<enter/newline>

        FILE *fp;
        int I;
        int c = 'Z';

       /* CODE FOR OPENING FILE HERE */

        for (I=0; I < 3; I++)
                putc(c, fp);
        c = getchar();
        c = getchar();
        putc(c, fp);
        putc(' ', fp);
        putc('\n', fp);
        fclose(fp);

18. Give the output of the following program code:

        int I;
        int J;
        int A[10][10];

        for (I=0; I < 10; I++) {
                for (J=0; J < 10; J++) {
                        A[I][J] = I*J;
                }
        }
        
        for (I=0; I < 10; I++) {
                printf("%d ", A[I][I]);
        }

19 . Given that your declarations are:
        char A[2][3];

    (a) Draw the matrix A, clearly labeling the rows, columns, and index values
        on the diagram.
    (b) Show the matrix after the statement:
              A[1][2] = 'a';
    (c) Show the matrix after the statement:
              A[1][0] = 'b';
    (d) What is wrong with the statement:
              A[2][3] = 'c';
    (e) Will the statement in (d) generate a syntax error in a C compiler?

[*** INSTRUCTOR NOTE: Question 19 was updated on 11/19/00 at 2:20am]


20. Give documented example code that illustrates the differences and similarities between
    passing an element of an array to a function versus passing a whole array to a function.
    Use 1D (one dimensional) arrays. Give both the function definition and the way the
    function is called.

21. In class we talked about "implicit pass by reference" in regards to passing whole arrays
    to functions. Clearly explain what "implicit pass by reference" means.

22. Write a function that replaces all elements of a 1D array that are equal to a value Num
    with another value, newNum. Pass the whole array, Num, and newNum as parameters
    to the function.

23. Show the steps involved and values of variables after each step with
   (a) insertion sort and (b) selection sort of the following values:
        10 2 100 30 40 -3

24. The "median" value of an array is the middle value. For example, if the array is
           1 3 90 100 300
    then the median value is 90. Note that in order for the median to make sense,
    the array must be sorted. Assume that you have been given a function called Sort with
    the following prototype:
         void Sort(int A[], int N);
    that sorts the first N elements of the array of int's A. Write a function that
    finds the median value of the array, after you have sorted it with the function
    Sort. Your function must make use of the fact that you have sorted the array.
    Make sure your function does something reasonable if N is an even number.
    Once your function finds the median, it should return that value as the result of
    calling the function.

25. Explain why, when using the binary search, the array being searched must be sorted
    beforehand.

26. Assume that the file named "file2.txt" contains the following information where
    1:, 2:, 3: etc. are numbers of the lines, and not part of the contents of the file
    and spaces are indicated with '_' (underscore) characters.

    1:39
    2:_1
    3:66
    4:4_
    5:
    6:

    Write a program that will read every character of a file and count the number of
    of characters in the file (excluding EOF). Your program should output the count
    of the number of all characters in the file. When your program is executed with
    file2.txt as the input file, what does it output? Make sure you include the
    setup and finishing statements relevant when dealing with files.

27. Write a program that writes the numbers: 1, 2, 3, ..., N to a file named "foo.txt".
    Prompt for and read N from the user of the program (from the keyboard).
    Make sure you include the setup and finishing statements relevant when dealing with
    files. The numbers should be written as text to the file. Each number should
    be separated by a space (not a newline) in the file. There should be no space and no
    newline in the file after the last number (N). If N is 0, the file should be empty
    after running your program.

28. What does the following program code do?

        FILE *instream;
        int c;
        int linenum = 1;
        int charcount = 0;

        if ((instream = fopen("file3.txt", "r")) == NULL) {
                printf("Unable to open file3.txt\n");
                exit(1);
        }

        while ((c = getc(instream)) != EOF) {
                if (c == '\n') {
                        printf("%3d: %d\n", linenum, charcount);
                        linenum++;
                        charcount = 0;
                } else {
                        charcount++;
                }
        }
        
        fclose(instream);

29. For the program code in question (28), there is a bug (feature?) that produces unusual
    behavior with certain contents for the file "file3.txt". Which files are these?
    Modify the program so that it no longer has this bug (or feature).

30. Imagine you are writing a program to control an insect robot. The robot is climbing
    a tree from the base of the tree upwards. It is looking for food. It is going to
    eat all the food that is on the tree. You are given the following functions to use:

         int CheckForFood(); /* returns a 1 only when there is food where robot is located */
         /* returns 0 otherwise */

         void EatFood(); /* eat food if there is food; see below */
         void TakeLeftBranch(); /* takes a left branch if it exists */
         void TakeRightBranch(); /* takes a right branch if it exists */

         int IsBranch(); /* returns 1 only if there is a left and a right branch */
         /* returns 0 otherwise */

    The robot insect climbs only very simple trees. At each branch point, there will be
    either both a left branch and a right branch, or no branch at all.
    Write a recursive function, using these above functions, that will have the insect
    eat all of the food on the tree. Note that if you call EatFood() and CheckForFood()
    was not true (i.e., there was no food at the current point on the tree) the insect
    will eat bark, and die. The insect robot starts at the bottom branching point
    of the tree, and after each time it moves with TakeLeftBranch() or TakeRightBranch(),
    it is at another branching point (that is, if there were branches) or at the end
    of a branch.

31. In a switch statement, what is the "default:" case? When does it get executed?

32. What does the following program code output?

        int val;

        for (val=-2; val < 6; val++) {
                if ((val >= 1) && ((val-1) < 5))
                        printf("alt1 ");
                else if ((val > -1) && (val <= 0))
                        printf("alt2 ");
                else
                        printf("alt3 ");
        }