1. In many programming languages strings are defined to be arrays of characters. Compare the consequences of this when a string variable is:
Consider string operations such as assignment, concatenation, and comparison.
Solution:
1. static array - We can do assignment between arrays that are the same size. But assignments from arrays of different sizes are tricky since we will have to ``pad'' or ``truncate'' the strings. We cannot concatenate two strings since that requires creating a bigger string. Comparison between arrays of the same size is easy since we can compare character by character. Again, we must be careful if the arrays are of different sizes and use a padding character (such as a blank space) during comparison. However, with static arrays, it is possible to do compile-time checks to make sure the arrays are of the same size and to disallow operations between arrays of different sizes.
2. dynamic array - The amount of space to allocate for a dynamic array is not decided until run-time. These will behave much the same as static arrays for strings, except that the compile-time check can no longer be performed (since we don't know until run-time how big a string will be).
3. flexible array - Assignment of any size string to any other size string is easy since strings do not have to be of any fixed size. Similarly it is no problem to concatenate and dynamically create larger strings. We may still have to pad with a blank character during comparison of unequal size strings.
So overall flexible arrays provide a more flexible implementation of strings, but these must be balanced with efficiency and ease of implementation. Perl and Icon use flexible array strings, but Pascal has a simpler and more efficient run-time storage manager, so it uses static arrays.
2. Write a program that prints out a table of Fibonacci numbers. Fibonacci numbers are defined by a series in which any element is the sum of the previous two elements.
Solution:
main() { int fib[24]; int i; fib[0] = 0; fib[1] = 1; for(i = 2; i < 24; i++) fib[i] = fib[i-1] + fib[i-2]; for (i = 0; i < 24; i++) printf("%3d %6d\n", i, fib[i]); }