Chapter 6. Arrays, Pointers, and Strings

Home

 

PROGRAM 61 : location.c

#include <stdio.h>

int main(void)
{
  int i = 7, *p;

  p = &i;
  printf("%s%d\n%s%p\n",
    " Value of i: ", *p,
    "Location of i: ", p);
  return 0;
}

 

PROGRAM 62 : main.c

#include <stdio.h>

void swap(int *, int *);

int main(void)
{
  int i = 3, j = 5;

  swap(&i, &j);
  printf("%d %d\n", i, j); /* 5 3 is printed */
  return 0;
}

PROGRAM 621 : swap.c

void swap(int *p, int *q)
{
  int tmp;

  tmp = *p;
  *p = *q;
  *q = tmp;
}

PROGRAM 63 : bubble.c

void bubble(int a[], int n) /* n is the size of a[] */
{
  int i, j;
  void swap(int *, int *);

  for (i = 0; i < n - 1; ++i)
    for (j = n - 1; j > i; --j)
      if (a[j-1] > a[j])
        swap(&a[j-1], &a[j]);
}

PROGRAM 64 : main.c

#include "array.h"

int main(void)
{
  int *a, n;

  srand(time(NULL)); /* seed the random number generator */
  printf("\n%s\n",
    "This program does the following repeatedly:\n"
    "\n"
    " 1 create space for an array of size n\n"
    " 2 fill the array with randomly distributed digits\n"
    " 3 print the array and the sum of its element\n"
    " 4 release the space\n");
  for ( ; ; ) {
    printf("Input n: ");
    if (scanf("%d", &n) != 1 || n < 1)
      break;
    putchar('\n');
    a = calloc(n, sizeof(int)); /* allocate space for a[] */
    fill_array(a, n);
    wrt_array(a, n);
    printf("sum = %d\n\n", sum_array(a, n));
    free(a);
  }
  printf("\nBye!\n\n");
  return 0;
}

PROGRAM 641 : fct.c

#include "array.h"

void fill_array(int *a, int n)
{
  int i;

  for (i = 0; i < n; ++i)
    a[i] = rand() % 19 - 9;
}

int sum_array(int *a, int n)
{
  int i, sum = 0;

  for (i = 0; i < n; ++i)
    sum += a[i];
  return sum;
}

void wrt_array(int *a, int n)
{
  int i;

  printf("a = [");
  for (i = 0; i < n; ++i)
    printf("%d%s", a[i], ((i < n - 1) ? ", " : "]\n"));
}

PROGRAM 642 :array.h

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void fill_array(int *a, int n);
int sum_array(int *a, int n);
void wrt_array(int *a, int n);

PROGRAM 65 : main.c

#include "mergesort.h"

int main(void)
{
  int i, key[] = { 4, 3, 1, 67, 55, 8, 0, 4,
    -5, 37, 7, 4, 2, 9, 1, -1 };

  mergesort(key, KEYSIZE);
  printf("After mergesort:\n");
  for (i = 0; i < KEYSIZE; ++i)
    printf("%4d", key[i]);
  putchar('\n');
  return 0;
}

PROGRAM 651 : merge.c

/*
// Merge a[] of size m and b[] of size n into c[].
*/

#include "mergesort.h"

void merge(int a[], int b[], int c[], int m, int n)
{
  int i = 0, j = 0, k = 0;

  while (i < m && j < n)
  if (a[i] < b[j])
    c[k++] = a[i++];
  else
    c[k++] = b[j++]; 
  while (i < m) /* pick up any remainder */
    c[k++] = a[i++];
  while (j < n)
    c[k++] = b[j++];
}

PROGRAM 652 : mergesort.c

/*
// Mergesort: Use merge() to sort an array of size n.
*/

#include "mergesort.h"

void merge(int *, int *, int *, int, int);

void mergesort(int key[], int n)

  int j, k, m, *w;

  for (m = 1; m < n; m *= 2)
    ;
  if (m != n) {
    printf("ERROR: Size of the array is not a power of 2 -    bye!\n");
    exit(1);
  }
  w = calloc(n, sizeof(int)); /* allocate workspace */
  for (k = 1; k < n; k *= 2) {
    for (j = 0; j < n - k; j += 2 * k)
       merge(key + j, key + j + k, w + j, k, k); /* merge into w */
      for (j = 0; j < n; ++j)
        key[j] = w[j]; /* write w back into key */
  }
  free(w); /* free the workspace */
}

PROGRAM 653 : mergesort.h

#include <stdio.h>
#include <stdlib.h>

#define KEYSIZE 16

void merge(int a[], int b[], int c[], int m, int n);
void mergesort(int key[], int n);

PROGRAM 66 : frogs.c

  char *s;
  int nfrogs;
  ..... /* get nfrogs from somewhere */
  s = (nfrogs == 1) ? "" : "s";
  printf("We found %d frog%s in the pond.\n", nfrogs, s);

PROGRAM 67 : word_cnt.c

/* Count the number of words in a string. */

#include <ctype.h>

int word_cnt(char *s)
{
  int cnt = 0;

  while (*s != '\0') {
    while (isspace(*s)) /* skip white space */
      ++s;
    if (*s != '\0') { /* found a word */
      ++cnt;
      while (!isspace(*s) && *s != '\0')
        ++s; /* skip the word */
    }
  }
  return cnt;
}

PROGRAM 68 : strlen.c

unsigned strlen(const char *s)
{
  register int n;

  for (n = 0; *s != '\0'; ++s)
    ++n;
  return n;
}

PROGRAM 69 : strcat.c

char *strcat(char *s1, const char *s2)
{
  register char *p = s1;

  while (*p)
    ++p;
  while (*p++ = *s2++)
    ;
  return s1;
}

 

PROGRAM 610 : sum2.c

int sum(int a[][5])
{
  int i, j, sum = 0;

  for (i = 0; i < 3; ++i)
    for (j = 0; j < 5; ++j)
      sum += a[i][j];
  return sum;
}

 

PROGRAM 611 :sum3.c

int sum(int a[][9][2])
{
  int i, j, k, sum = 0;

  for (i = 0; i < 7; ++i)
    for (j = 0; j < 9; ++j)
      for (k = 0; k < 2; ++k)
        sum += a[i][j][k];
  return sum;
}

 

PROGRAM 612 : main.c

/* Sort words lexicographically. */

#include "sort.h"

int main(void)
{
  char word[MAXWORD]; /* work space */
  char *w[N]; /* an array of pointers */
  int n; /* number of words to be sorted */
  int i;

  for (i = 0; scanf("%s", word) == 1; ++i) {
    if (i >= N)
      error_exit_too_many_words();
    if (strlen(word) >= MAXWORD)
      error_exit_word_too_long();
    w[i] = calloc(strlen(word) + 1, sizeof(char));
    if (w[i] == NULL)
      error_exit_calloc_failed();
    strcpy(w[i], word);
  }
  n = i;
  sort_words(w, n); /* sort the words */
  wrt_words(w, n); /* write sorted list of words */
  return 0;
}

 

PROGRAM 6121 : sort_words.c

#include "sort.h"

void sort_words(char *w[], int n) /*n elements are to be sorted */
{
  int i, j;

  for (i = 0; i < n; ++i)
    for (j = i + 1; j < n; ++j)
      if (strcmp(w[i], w[j]) > 0)
        swap(&w[i], &w[j]);
}

 

PROGRAM 6122 : swap.c

#include "sort.h"

void swap(char **p, char **q)
{
  char *tmp;

  tmp = *p;
  *p = *q;
  *q = tmp;
}

 

PROGRAM 6123 : wrt.c

#include "sort.h"

void wrt_words(char *w[], int n)
{
  int i;

  for (i = 0; i < n; ++i)
    printf("%s\n", w[i]);
}

 

PROGRAM 6124 : error.c

#include "sort.h"

void error_exit_calloc_failed(void)
{
  printf("%s",
    "ERROR: The call to calloc() failed to\n"
    " allocate the requested memory - bye!\n");
  exit(1);
}

void error_exit_too_many_words(void)
{
  printf("ERROR: At most %d words can be sorted - bye!\n", N);
  exit(1);
}

void error_exit_word_too_long(void)
{
  printf("%s%d%s",
    "ERROR: A word with more than ", MAXWORD, "\n"
    " characters was found - bye!\n");
  exit(1);
}

 

PROGRAM 6125 : sort.h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXWORD 50 /* max word size */
#define N 300 /* array size of w[] */

void error_exit_calloc_failed(void);
void error_exit_too_many_words(void);
void error_exit_word_too_long(void);
void sort_words(char *w[], int n);
void swap(char **p, char **q);
void wrt_words(char *w[], int n);

 

PROGRAM 613 : echo.c

/* Echoing the command line arguments. */

#include <stdio.h>

int main(int argc, char *argv[])
{
  int i;

  printf("argc = %d\n", argc);
  for (i = 0; i < argc; ++i)
  printf("argv[%d] = %s\n", i, argv[i]);
  return 0;
}

 

PROGRAM 614 : ragged.c

#include <stdio.h>

int main(void)
{
  char a[2][15] = {"abc:", "a is for apple"};
  char *p[2] = {"abc:", "a is for apple"};

  printf("%c%c%c %s %s\n%c%c%c %s %s\n",
    a[0][0], a[0][1], a[0][2], a[0], a[1],
    p[0][0], p[0][1], p[0][2], p[0], p[1]);
  return 0;
}

 

PROGRAM 615 : main.c

#include "sum_sqr.h"

int main(void)
{
  printf("%s%.7f\n%s%.7f\n",
    " First computation: ", sum_square(f, 1, 10000),
    "Second computation: ", sum_square(sin, 2, 13));
  return 0;
}

 

PROGRAM 6151 : fct.c

double f(double x)
{
  return 1.0 / x;
}

 

PROGRAM 6152 : sum_sqr.c

double sum_square(double f(double), int m, int n)
{
  int k;
  double sum = 0.0;

  for (k = m; k <= n; ++k)
    sum += f(k) * f(k);
  return sum;
}

 

PROGRAM 6153 :sum_sqr.h

#include <math.h>
#include <stdio.h>

double f(double);
double sum_square(double (*)(double), int, int);

 

PROGRAM 616 : main.c

/* Find a root of f() by the bisection method. */

#include "find_root.h"

int cnt = 0;
const dbl eps = 1e-13; /* epsilon, a small quantity */

int main(void)
{
  dbl a = -10.0;
  dbl b = +10.0;
  dbl root;

  assert(f(a) * f(b) <= 0.0);
  root = bisection(f, a, b); /* recursive fct call */
  printf("%s%d\n%s% .15f\n%s% .15f\n",
    "No. of fct calls: ", cnt,
    "Approximate root: ", root,
    " Function value: ", f(root));
  return 0;
}

 

PROGRAM 6161 : bisection.c

#include "find_root.h"

dbl bisection(dbl f(dbl x), dbl a, dbl b)
{
  dbl m = (a + b) / 2.0; /* midpoint */

  ++cnt; /* # of fct calls */
  if (f(m) == 0.0 || b - a < eps)
    return m;
  else if (f(a) * f(m) < 0.0)
    return bisection(f, a, m);
  else
    return bisection(f, m, b);
}

 

PROGRAM 6162 : find_root.h

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

typedef double dbl;

extern int cnt;
extern const dbl eps; /* epsilon, a small quantity */

dbl bisection(dbl f(dbl x), dbl a, dbl b);
dbl f(dbl x);

 

PROGRAM 6163 : fct.c

#include "find_root.h"

dbl f(dbl x)
{
  return (x * x * x * x * x - 7.0 * x - 3.0);
}

 

PROGRAM 617 : main.c

/* Use bisection to solve the Kepler equation. */

#include "kepler.h"

int cnt = 0;
const dbl eps = 1e-15; /* epsilon, a small quantity */
const dbl e = 0.5; /* a parameter in the Kepler eqn */
const dbl m = 2.2; /* a parameter in the Kepler eqn */

int main(void)
{
  dbl a = -100.0;
  dbl b = +100.0;
  dbl root;

  assert(kepler(a) * kepler(b) <= 0.0);
  root = bisection(kepler, a, b); /* recursive fct call */
  printf("%s%d\n%s% .15f\n%s% .15f\n",
    "No. of fct calls: ", cnt,
    "Approximate root: ", root,
    " Function value: ", kepler(root));
  return 0;
}

 

PROGRAM 6171 : bisection.c

#include "kepler.h"

dbl bisection(dbl f(dbl x), dbl a, dbl b)
{
  dbl m = (a + b) / 2.0; /* midpoint */

  ++cnt; /* # of fct calls */
  if (f(m) == 0.0 || b - a < eps)
    return m;
  else if (f(a) * f(m) < 0.0)
    return bisection(f, a, m);
  else
    return bisection(f, m, b);
}

 

PROGRAM 6172 : kepler.h

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

typedef double dbl;

extern int cnt;
extern const dbl eps; /* epsilon, a small quantity */
extern const dbl e; /* a parameter in the Kepler eqn */
extern const dbl m; /* a parameter in the Kepler eqn */

dbl bisection(dbl f(dbl x), dbl a, dbl b);
dbl kepler(dbl x);

 

PROGRAM 6173 : kepler.c

#include "kepler.h"

dbl kepler(dbl x)
{
  return (x - e * sin(x) - m);
}

 

PROGRAM 618 : main.c

/* Use bisection to find roots. */

#include "find_roots.h"

int cnt = 0;
const dbl eps = 1e-13; /* epsilon, a small quantity */

int main(void)
{
  int begin_cnt;
  int i;
  int nfct_calls;
  dbl a = -100.0;
  dbl b = +100.0;
  dbl root;
  dbl val;
  pfdd f[N] = {NULL, f1, f2, f3};

  for (i = 1; i < N; ++i) {
    assert(f[i](a) * f[i](b) <= 0.0);
    begin_cnt = cnt;
    root = bisection(f[i], a, b);
    nfct_calls = cnt - begin_cnt;
    val = f[i](root);
    printf("%s%d%s% .15f\n%s%d%s% .15f\n%s%3d\n\n",
      "For f[", i, "](x) an approximate root is x0 = ", root,
      " Fct evaluation at the root: f[", i, "](x0) = ", val,
      " Number of fct calls to bisection() =", nfct_calls);
  }
  return 0;
}

 

PROGRAM 6181 : bisection.c

#include "find_roots.h"

dbl bisection(pfdd f, dbl a, dbl b)
{
  dbl m = (a + b) / 2.0; /* midpoint */

  ++cnt; /* # of fct calls */
  if (f(m) == 0.0 || b - a < eps)
    return m;
  else if (f(a) * f(m) < 0.0)
    return bisection(f, a, m);
  else
    return bisection(f, m, b);
}

 

PROGRAM 6182 : find_root.h

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

#define N 4 /* size of array of ptrs to fcts */

typedef double dbl;

/*
// Create the type "ptr to fct taking a dbl and returning a dbl."
*/
typedef dbl (*pfdd)(dbl);

extern int cnt;
extern const dbl eps; /* epsilon, a small quantity */

dbl bisection(pfdd f, dbl a, dbl b);
dbl f1(dbl x);
dbl f2(dbl x);
dbl f3(dbl x);

 

PROGRAM 6183 : fct.c

#include "find_roots.h"

dbl f1(dbl x)
{
  return (x*x*x - x*x + 2.0*x - 2.0);
}

dbl f2(dbl x)
{
  return (sin(x) - 0.7*x*x*x + 3.0);
}

dbl f3(dbl x)
{
  return (exp(0.13*x) - x*x*x);
}

 


[Last Update: 2001.5.11] Dongseo University Cyber Campus