EE150 - Spring 1996

Sample Midterm #2
Solutions

You should resist the temptation to look at these answers until after you have first tried to solve the problems in the same midterm!
Jump To Solution For Problem: [1 | 2 | 3 | 4]
------

Problem #1

Part A

The output is:

90
80

Here is the reason why.

The for loop is designed to take i from 7 down through 0. Each time through the loop, the first if tests whether the table element indexed by i is greater than 75 and prints the value if that's case. The second if tests whether that same element is negative and exits the loop early if it is. So, this program is working its way backwards through the array, printing each element that is greater than 75, and stopping as soon as it encounters a negative array element.

The problem.

Part B

The output is:

0-b
1-b
2-b
3-a
3-b
4-a
4-b
5-b

Here is the reason why. The for loop runs i from 0 up to 5, stopping when i gets to be 6. The first if checks whether i is between 3 and 4, and prints i and "a" if it is. The second if checks whether i is greater than or equal to 3 or less than or equal to 4. The first condition is true for 3, 4, and 5; the second is true for 0, 1, 2, 3, and 4. As a result, it writes a b for all values of i we try, and also writes an a first when i is 3 or 4.

The problem.

------

Problem #2

Part A

The changes are:

The problem.

Part B

The changes are:

The problem.

------

Problem #3

One solution is the following:

#include <stdio.h>

main()
{
  int readline();

  int length;
  int lines = 0;
  int total_lengths = 0;

  while ((length = readline()) != -1)
  {
    printf("%i\n", length);
    total_lengths += length;
    lines++;
  }
  printf("There were %i bars with an average length of %i\n",
          lines, (lines != 0) ? total_lengths / lines : 0);
  return 0;
}

int readline()
{
  int c;
  int count;

  if ((c = getchar()) == EOF)      /* EOF causes -1 to be returned. */
    return -1;

  for (count = 0; c != '\n'; count++)
    c = getchar():
  return count;
}

The problem.

------

Problem #4

One solution for this function (that makes the assumption that n will never be zero).

int maxvalue(int table[], int n)
{
  int i;
  int max;

  max = table[0];
  for (i = 1; i < n; i++)
    if (table[i] > max)
      max = table[i];
  return max;
}

The problem.

------

[EE150 Home Page | EE150 Exam Information Page | Top Of Page]