Exercise 8 page 331 - solution with pointers and a single for loop.

Solution index                   Textual C program


#include <stdio.h>

#define ROWS 5
#define COLS 4

int main(void) {

  double table [ROWS][COLS] =
    {{ 3.1,  5.5,  2.7, 19.3},
     { 0.2, 15.4, 16.9, -3.0},
     { 7.2,  5.4, 18.0, 13.7},
     {17.8, 15.4, 18.6,  3.0},
     { 7.1, -5.4,  8.7,  333.3}};

  double min_el = table[0][0], max_el = table[0][0];
  double *table_ptr = &table[0][0];

  int i, count; 
  count = sizeof(table) / sizeof(double);

  for(i = 0; i < count; i++){
    double *dptr = (table_ptr + i);
    if (*dptr < min_el) min_el = *dptr;
    if (*dptr > max_el) max_el = *dptr;
  };

  printf("\nThe minimun element is %f, and the maxium is %f\n\n", min_el, max_el);
  return 0;
}

We are about to find the minimum and the maximum element in a two dimensional array. We will give an alternative solution to our main solution, which is based on two nested for loops. In the present solution, we will only use a single for loop, and pointers. Here we only explain the new aspectes relative to the other solution.
 

double *table_ptr = &table[0][0];
We declare a pointer to an double and initializes it to a pointer to the element table[0][0].
 

count = sizeof(table) / sizeof(double);
We calculate the number of elements in the table, based on the table size (measuered in bytes) and based on the size of a double on our machine. In general, this is very useful.
 

for(i = 0; i < count; i++){
  double *dptr = (table_ptr + i);
  if (*dptr < min_el) min_el = *dptr;
  if (*dptr > max_el) max_el = *dptr;
};
We traverse all elements in the array using a single for loop. dptr is a pointer variable in the block which makes up the body of the for loop. The initial value of dptr is as a pointer to table[0][0]. We increment the pointer while we iterate. This is pointer arithmetic. The body of the for loop is similar to the body of the other solution. We know how many elements to traverse, namely the number corresponding to value in the variable count.
 


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