Exercise 7 page 297

Solution index                   Textual C program


#include <stdio.h>

void order_chars(char *c1, char *c2, char *c3);
void swap(char *p, char *q);

int main(void) {

  char c1 = 'c', c2 = 'b', c3 = 'd';

  printf("%c, %c, %c\n", c1, c2, c3);
  order_chars(&c1, &c2, &c3);
  printf("%c, %c, %c\n", c1, c2, c3);
  
  return 0;
}

void order_chars(char *c1, char *c2, char *c3){
  if (*c3 < *c2) swap(c2,c3);
  if (*c2 < *c1) swap(c1,c2);  
  if (*c3 < *c2) swap(c2,c3);  
}

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

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

                               

void order_chars(char *c1, char *c2, char *c3);
void swap(char *p, char *q);
We define prototypes of the two functions order_chars and swap, such that they are known by the main method.
 

int main(void) {

  char c1 = 'c', c2 = 'b', c3 = 'd';

  printf("%c, %c, %c\n", c1, c2, c3);
  order_chars(&c1, &c2, &c3);
  printf("%c, %c, %c\n", c1, c2, c3);
  
  return 0;
}
We define three character variables c1, c2, and c3. We pass the addresses of these variables to order_chars. In that way, order_chars can change the values of the variables for us, which is exactly what we want. Recall that we go for a re-ordering of the values of c1, c2, and c3 such that their values appear as sorted.
 

void order_chars(char *c1, char *c2, char *c3){
  if (*c3 < *c2) swap(c2,c3);
  if (*c2 < *c1) swap(c1,c2);  
  if (*c3 < *c2) swap(c2,c3);  
}
The function order_chars receives three pointers to chars. In other words, it uses call by reference parameters. First it compares the values of *c3 and *c2. Hereby the two last characters passed to order_chars are compared. If they are out of order, we use the function swap to exchange their values. Next, *c2 and *c1 are compare and maybe swaped. These two steps ensure that *c1 is the smallest. The next step ensures that *c2 is smaller than *c3. If not, we swap these too. Then we are done.

We can notice that our sorting strategy is quite similar to bubble sort applied on a three element array.
 

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

   tmp = *p;
   *p = *q;
   *q = tmp;
}
The function is swap we have seen before, so we will not comment on it here. It is explained in the text book.
 


Generated: Wednesday, March 29, 2006, 12:33:30
This program dissection page is generated from an XML-in-LAML source file