Answers to Sample Final
- Returns a pointer the the last occurance of c in s.
- illegal assignment
- illegal assignment
- It prints the character 'B', then a newline, then the character 'C',
then another newline.
- The argument to a_again is passed by copy,
not by reference. You need to pass a pointer:
void a_again(int *acount)
register int c;
int counter = 0;
while((c = getchar()) != EOF)
if (c == 'a' || c == 'A')
- Here is one solution.
int dot( int a, int b, int n )
int sum = 0;
for(i = 0; i < n; i++)
sum += a[i] * b[i];
A good practise exercise is to write a recursive version of this routine.
(Hint: the base case is where n = 1, becauseyou
return the product of the single elements in the vectors a and
- The problem is that the order of evaluation of function arguments
is undefined, so the call f(++i, ++i) could be either
f(6, 7) or f(7, 6). Hence the two possible answers are
- Here is one solution:
int sum(int a, int b)
return(a == b ? a : (a + sum(a+1, b)));
- This adds the even numbers from 0 to 102 inclusive.
- No. x is 0 since the while condition is initially false.
- No. This adds the odd numbers from 0 to 100 inclusive.
- This function emulates strcmp.
It returns the numerical difference between the first mismatched character
in strings s and t; it returns 0 if the strings are the
- Three problems are:
- The c to which the value of getchar() is assigned
is declared as a char rather than an int.
Now, EOF is the integer -1; so when it is assigned
to a character, only the low 8 bits are used.
When c is compared to EOF,
c's value is changed to an integer.
If c is signed, it becomes -1; if c is
unsigned, it becomes 255 (because the 8 low-order bits are the same
as the contents of c, and the high-order 24 bits are 0).
In the former case, the comparison in the while loop fails
and the loop ends. In the latter case, the comparison succeeds (as 255 != -1)
and the loop never terminates.
As char without any modifier may be either signed
or unsigned (it is implementation dependent),
to fix this problem either c must be declared as
unsigned char c or (better) as int c.
- The return value of malloc() is not checked.
The check should be added.
- Adding two pointers is not legal in ANSI and is inherently non-portable.
The expression (buf + p) / 2 should be
buf + (p - buf) / 2.
Send email to
Department of Computer Science
University of California at Davis
Davis, CA 95616-8562
Page last modified on 12/4/97