CSCI 159: exam practice questions sample solutions

Question 1: Basic array use in a function

Write a function that takes two parameters: an array of floats and its size, n, and returns the sum of all the positive values in the array.
Sample answer:
float sum(float nums[], int n)
{
   float total = 0;
   for (int pos = 0; pos < n; pos++) {
       if (nums[pos] > 0) {
          total = total + nums[pos];
       }
   }
   return total;
}

Question 2: Arrays and recursion [challenging]

I'll typically have one question per exam where I combine two different topics in a way you haven't seen so far: this is a good example of such a question.

Try solving question 1 again, but this time using recursion instead of a loop to go through the array.

Suggested recursive structure for your function:
if n is less than 0 you can simply return 0,
otherwise
   1. have your sum function call itself
          passing it the same array, but passing n-1 as the size,
      thus the result it returns should be the sum of the first N-1 positive elements
   2. if arr[n-1] is a positive number then
         add it to the result from step 1
   3. return the result
Sample answer:
float sum(float nums[], int n)
{
   // base case, no values to process, quit and return 0
   if (n <= 0) {
      return 0;
   }
   // general case:
   //    calls itself on the first n-1 elements
   //    then decides whether or not we need to include nth element
   //       (based on whether or not the nth element is positive)
   float result = sum(nums, n-1);
   if (nums[n-1] > 0) {
      result = result + nums[n-1];
   }
   return result;
}