Solutions to Homework Assignment #7

1.假設副程式 bar 被呼叫時,其實際參數的值為大於或等於 0 的整數。將下列的遞迴副程式 (recursive subprogram) 改寫為迴圈的副程式 (loop subprogram)

int bar(int p) {

  if (p==1) return 0;

  else if (p==2) return 1;

  else if (p==3) return 2;

  else return bar(p-1)+bar(p-2)+bar(p-3);

}

Answer:

int bar1(int p) {
  int a, b, c, result, i;
  if (p==1) result = 0;
  else if (p==2) result = 1;
  else if (p==3) result = 2;

  else {

    a = 0;
    b = 1;
    c = 2;
    result = 0;
    for (i=4; i<=p; i++) {
      result = a + b + c;
      a = b;
      b = c;
      c = result;
  } } 
  return result;
}

2. 將下列C語言迴圈副程式改寫為遞迴副程式

float sum(float *data, int count) {

  float s = 0;

  while (count >0) {

    s += data[count-1];

    count--;

  }

  return s;

}

Answer:

float sum(float *data, int count) {

  if (count==0) return 0;

  else return sum(data, count-1)+data[count-1];

}