|  |   | 
|  | 
| 
 |  Chapter 9Answers to Selected Exercises2. [was #2] 
int check(int x, int y, int n)
{
  return (x >= 0 && x <= n - 1 && y >= 0 && y <= n - 1);
}
4. [was #4] 
int day_of_year(int month, int day, int year)
{
  int num_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  int day_count = 0, i;
  for (i = 1; i < month; i++)
    day_count += num_days[i-1];
  /* adjust for leap years, assuming they are divisible by 4 */
  if (year % 4 == 0 && month > 2)
    day_count++;
  return day_count + day;
}
Using the expression  year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) 6. [was #6; modified] 
int digit(int n, int k)
{
  int i;
  for (i = 1; i < k; i++)
    n /= 10;
  return n % 10;
}
8. [was #8] (a) and (b) are valid prototypes. (c) is illegal, since it doesn't specify the type of the
parameter. (d) incorrectly specifies that  10. [was #10] (a) 
int largest(int a[], int n)
{
  int i, max = a[0];
  for (i = 1; i < n; i++)
    if (a[i] > max)
      max = a[i];
  return max;
}
(b) 
int average(int a[], int n)
{
  int i, avg = 0;
  for (i = 0; i < n; i++)
    avg += a[i];
  return avg / n;
}
(c) 
int num_positive(int a[], int n)
{
  int i, count = 0;
  for (i = 0; i < n; i++)
    if (a[i] > 0)
      count++;
  return count;
}
15. [was #12; modified] 
double median(double x, double y, double z)
{
  double result;
  if (x <= y)
    if (y <= z) result = y;
    else if (x <= z) result = z;
    else result = x;
  else {
    if (z <= y) result = y;
    else if (x <= z) result = x;
    else result = z;
  }
  return result;
}
17. [was #14] 
int fact(int n)
{
  int i, result = 1;
  for (i = 2; i <= n; i++)
    result *= i;
  return result;
}
19. [was #16] The following program tests the  
#include <stdio.h>
void pb(int n);
int main(void)
{
  int n;
  printf("Enter a number: ");
  scanf("%d", &n);
  printf("Output of pb: ");
  pb(n);
  printf("\n");
  return 0;
}
void pb(int n)
{
  if (n != 0) {
    pb(n / 2);
    putchar('0' + n % 2);
  }
}
 Enter a number: 53 Output of pb: 110101 
A trace of  
 Copyright © 2008, 1996 W. W. Norton & Company, Inc. All rights reserved. |