Comp 1672, Winter 2003 Homework Assignment 1 Solutions 1a) The colon on the 3rd line should be a semi-colon. The (x=1) on the 4th line should be (x==1). The "otherwise" on the 6th line should be "else" 1b) The "For" should be "for" The commas should be semicolons The x++ should be x-- instead (otherwise you get an infinite loop lc) The case 0 segment is missing a break. (Even better, put a break statement at the end of each case.) 1d) The logic in the while statement is wrong. It should say while (answer < 0 || answer > 1) 2. For each value of i, 5-i+1 X's are output. This gives 6+5+4+3+2=20 X's 3. The trick here is that there is a semi-colon after the for statement. This means that the for-loop has an empty body - NOTHING happens each repetition of the for-loop, except that ctr is incremented. At the final increment, ctr==20, and at that point the for-loop terminates. Then ctr is output. The value output is 20. 4. int power(int base, int exponent) { int i; int result=1; for (i=1; i <= exponent ; i++) result *= base; return result; } 5. // return the value of the nth fibonacci number. The value of n should // be 1 or greater. Return 0 for invalid inputs. int fibonacci(int n) { int i, prev(1), prevprev(1), current; if (n <=0) return 0; // invalid input - return 0 if (n == 1 || n == 2) // The first two values of the sequence return 1; // are both equal to 1 for (i=3; i <= n; i++) { // If n >= 3, then calculate all values // starting at 3 until we get to n current = prev+prevprev; // Add previous two values to get the next prevprev=prev; // Then update the two previous ones prev=current; } return current; }