Solution to question 11

#include <stdio.h>

int numOdds(int i, int j) {
int tmp;

// Swap i and j if necessary to ensure that i <= j.

if (j < i) {
tmp = i; i = j; j = tmp;
}

// Make i the largest odd number <= the original i.

if (i % 2 == 0) i--;

// Make j the smallest odd number >= the original j.

if (j % 2 == 0) j++;

// Allow for the special case that the original i and j were equal and odd.

if (i == j) j += 2;

// Finally, calculate the result.
return (j - i)/2 - 1;
}

int main(void) {
printf("%d %d %d\n", 3, 7, numOdds(3,7));
printf("%d %d %d\n", 2, 4, numOdds(2,4));
printf("%d %d %d\n", 4, 2, numOdds(4,2));
printf("%d %d %d\n", 0,10, numOdds(0,10));
printf("%d %d %d\n",-1, 0, numOdds(-1,0));
printf("%d %d %d\n", 1, 1, numOdds(1,1));
printf("%d %d %d\n", 1,-1, numOdds(1,-1));
printf("%d %d %d\n", 1,-2, numOdds(1,-2));
return 0;
}

Solution to question 12

#include <stdio.h>
#include <assert.h>

typedef struct {
int hour;
int minute;
float second;
} time;

void addTimesAndPrint(time t1, time t2) {
time t;

// Verify that t1 and t2 are valid times.

assert(t1.hour >= 0 &&
t1.hour < 24 &&
t1.minute >= 0 &&
t1.minute < 60 &&
t1.second >= 0.0F &&
t1.second < 60.0F);

assert(t2.hour >= 0 &&
t2.hour < 24 &&
t2.minute >= 0 &&
t2.minute < 60 &&
t2.second >= 0.0F &&
t2.second < 60.0F);

// Now add them, without worrying about overflow.

t.hour = t1.hour + t2.hour;
t.minute = t1.minute + t2.minute;
t.second = t1.second + t2.second;

// Now correct for possible overflows.

if (t.second >= 60.0F) {
t.minute++;
t.second -= 60.0F;
}

if (t.minute >= 60) {
t.hour++;
t.minute -= 60;
}

printf("%02d:%02d:%04.1f\n", t.hour, t.minute,t.second);
}


// A main program to test our function.

int main(void) {

time t1 = {1, 30, 10.0};
time t2 = {2, 30, 51.1};
addTimesAndPrint(t1,t2);

time t3 = {23, 59, 59.9};
time t4 = {23, 59, 59.9};
addTimesAndPrint(t3,t4);

time t5 = {1, 30, 10.0};
time t6 = {-1, 30, 61.0};
addTimesAndPrint(t5,t6);

return 0;
}

Solution to question 13

#include <stdio.h>

char *strcat(char *dest, char *src) {
char *p;

// Start at the first byte of the "dest" string.

p = dest;

// Increment our way through the string until we hit a
// zero (i.e, the terminating null byte).

while (*dest) {
dest++;
}

// Now increment our way through the "src" string, until
// we reach the end of it, copying bytes to "dest" as we go.

while (*src) {
*dest++ = *src++;
}

// Null-terminate the "dest" string.

*dest = 0;

// Return a pointer to the first byte of "dest".

return p;
}

int main(void) {
char dest[100] = "one";
char src[] = "two";

printf("the result is \"%s\"\n", strcat(dest, src));
return 0;
}