Assignment 1, Solutions
Part of
the homework for 22C:60 (CS:2630), Spring 2013
|
An answer cannot be posted.
Homework questions based on prerequisite material:
- Background: Consider this function in C (but C++, Java and C# look very similar):
int funct( int i ) { /* warning! This is not the fibonacci series */ if (i > 1) { i = funct(i - 1) - funct(i - 2); } return i; }Problem: Make a table of the values of funct(i) for values of i ranging from 0 to 10. (1 point)
i 0 1 2 3 4 5 6 7 8 9 10 funct(i) 0 1 1 0 -1 -1 0 1 1 0 -1
- Background: Consider these functions in C (but C++, Java and C# look very similar):
char digit_a( int i ) { const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; return digits[i % 10]; } char digit_b( int i ) { return (i % 10) + '0'; }A Question: These functions do essentially the same thing for non-negative values of i. Why do they behave very differently for negative values? (1 point)
In most C and C++ implementations, the remainder after division of a negative number by a positive number will be zero or negative. In Java it will always be zero or negative. Therefore, digit_a() will return a value selected by an out-of-bounds array index -- raising an exception in Java, or returning nonsense in C or C++.
In contrast the value returned by digit_b() is well defined in this case. We are adding a value in the range -9 to 0 to the character '0'. Inspection of the ASCII character table reveals that this will be one of the characters in the string "'()*+,-./0" (presented in order for index values from -9 to 0).
Homework questions based Chapter 2 of the text:
- A Problem: Give the 7-bit ASCII representation of the text "January 2012" Don't include the quotes. Give your result as a column of binary numbers, one per character. (1 point)
1001010 1100001 1101110 1110101 1100001 1110010 1111001 0100000 0110010 0110000 0100001 0100010Actually, the question had an error in it. The correct answer to the question as it should have been posed would have ended in 0100011.