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 12

Answers to Selected Exercises

2. [was #2] The statement is illegal because pointers cannot be added. Here's a legal statement that has the desired effect:

middle = low + (high - low) / 2;

The value of (high - low) / 2 is an integer, not a pointer, so it can legally be added to low.

4. [was #6]

int *top_ptr;

void make_empty(void)
{
  top_ptr = &contents[0];
}

bool is_empty(void)
{
  return top_ptr == &contents[0];
}

bool is_full(void)
{
  return top_ptr == &contents[STACK_SIZE];
}

6. [was #10; modified]

int sum_array(const int a[], int n)
{
  int *p, sum;

  sum = 0;
  for (p = a; p < a + n; p++)
    sum += *p;
  return sum;
}

13. [was #12; modified]

#define N 10

double ident[N][N], *p;
int num_zeros = N;

for (p = &ident[0][0]; p <= &ident[N-1][N-1]; p++)
  if (num_zeros == N) {
    *p = 1.0;
    num_zeros = 0;
  } else {
    *p = 0.0;
    num_zeros++;
  }

15. [was #14]

int *p;

for (p = temperatures[i]; p < temperatures[i] + 24; p++)
  printf("%d ", *p);

Answers to Selected Programming Projects

1. [was #4]

(a)

#include <stdio.h>

#define MSG_LEN 80     /* maximum length of message */

int main(void)
{
  char msg[MSG_LEN];
  int i;

  printf("Enter a message: ");
  for (i = 0; i < MSG_LEN; i++) {
    msg[i] = getchar();
    if (msg[i] == '\n')
      break;
  }

  printf("Reversal is: ");
  for (i--; i >= 0; i--)
    putchar(msg[i]);
  putchar('\n');

  return 0;
}

(b)

#include <stdio.h>

#define MSG_LEN 80     /* maximum length of message */

int main(void)
{
  char msg[MSG_LEN], *p;

  printf("Enter a message: ");
  for (p = &msg[0]; p < &msg[MSG_LEN]; p++) {
    *p = getchar();
    if (*p == '\n')
      break;
  }

  printf("Reversal is: ");
  for (p--; p >= &msg[0]; p--)
    putchar(*p);
  putchar('\n');

  return 0;
}

3. [was #8]

#include <stdio.h>

#define MSG_LEN 80     /* maximum length of message */

int main(void)
{
  char msg[MSG_LEN], *p;

  printf("Enter a message: ");
  for (p = msg; p < msg + MSG_LEN; p++) {
    *p = getchar();
    if (*p == '\n')
      break;
  }

  printf("Reversal is: ");
  for (p--; p >= msg; p--)
    putchar(*p);
  putchar('\n');

  return 0;
}

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

Google
 
Web knking.com