knking.com -- Programming Language Books and Training

 C C++ Java

Books by K. N. King

Home
Books by K. N. King
Short courses
Recommended books
Recommended links
FAQ

C Programming: A Modern Approach (Second Edition)

Chapter 23

Answers to Selected Exercises

1. [was #2; modified]

double round_nearest(double x, int n)
{
  double power = pow(10.0, n);

  if (x < 0.0)
    return ceil(x * power - 0.5) / power;
  else
    return floor(x * power + 0.5) / power;
}

6. [was #6]

(a) memmove
(b) memmove (we can't use strcpy because its behavior is undefined when the source of the copy overlaps with the destination)
(c) strncpy
(d) memcpy

8. [was #8]

int numchar(const char *s, char ch)
{
  int count = 0;

  s = strchr(s, ch);
  while (s != NULL) {
    count++;
    s = strchr(s + 1, ch);
  }

  return count;
}

10. [was #10]

if (strstr("foo#bar#baz", str) != NULL) …

The assumptions are that str is at least three characters long and doesn't contain the # character.

11. [was #12] memset(&s[strlen(s)-n], '!', n);

Answers to Selected Programming Projects

2. [was #4; modified]

#include <ctype.h>
#include <stdbool.h>   /* C99 only */
#include <stdio.h>

int main(void)
{
  bool nonblank_seen = false;
  int ch;

  while ((ch = getchar()) != EOF) {
    if (nonblank_seen)
      putchar(ch);
    else if (!isspace(ch)) {
      nonblank_seen = true;
      putchar(ch);
    }
    if (ch == '\n')
      nonblank_seen = false;
  }

  return 0;
}

Copyright © 2008, 1996 W. W. Norton & Company, Inc. All rights reserved.

Google
 
Web knking.com