Fundamentals of Programming using C++


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 15 - Array processing routines.

General.

In the last topic you learned how to create an array of integers or floating point values and we covered, very briefly, how to store values into these arrays and print them on standard output.

In order to extend that work we now look at a number of useful (and well-known) methods of processing arrays. To do this, it is convenient to first learn about for loops, which are the quickest and easiest kind of loops with which to traverse an array.

For loops.

You already know how to write a simple while loop, which prints the numbers from 1 to 10, like this:

  int i = 1;      // initial setting[1]

  while( i <= 10) // condition[2]
  {
    cout << i << endl;

    i++;          // increment[3]
  }

As the comments in this fragment of code show, there are three important features of a while loop:

  1. the initial setting of the counting variable;
  2. the condition which is used to decide when the loop iterates and when it stops, and
  3. the incrementing statement which increases the counting variable.

These three features are combined into the syntax of the for loop. A for loop which does exactly the same work as the while loop above would look like this:

  for( int i = 1; i <= 10; i++)  //note semicolons between parts - not commas!
    cout << i << endl;

From this example you might deduce that a for loop is really a while loop with a different syntax - and this is true!

Note that we do not need opening and closing braces to enclose the body of this loop because it (the body of the loop) only contains one statement.

Passing arrays to functions.

The array processing routines we will look at can best be done by encapsulating each one in a separate C++ function. In each case, we will have to pass the array, as a parameter, to the function; the function will process the array in a particular way and return the required output from this processing back to the caller of the function.

When an array is passed to a function as a parameter, the function can access the elements of the array but the function does not automatically know how many elements are in the array; so, we will also need to pass the length of the array to the function.

Array processing routines.

Summing an array.

The following program creates an array of integers, fills it with values and passes it to a function which sums the values.

  // Summing an array

  #include <iostream.h>

  int sum_array( int list[], int length );

  void main( void )
  {
    int list[15]; // the array

    // fill the array
    for(int i = 0; i < 15; i++)
    {
      cout << "Enter a value for element " << i << " ";
      cin >> list[i];
    }

    int total = sum_array( list, 15 ); // function call

    cout << "The sum of the array is " << total << endl;
  }


  int sum_array( int list[], int length )
  {
    int total = 0;
    for( int i = 0; i < length; i++ )
      total += list[i];
    return total;
  }

Note carefully how the name of the array is written in the formal parameter list of the function:

  function_name( int list[], ...)

The square brackets [] are necessary in the formal parameters so that the compiler realises that the variable list is an array of integers, not just a single integer.

Maximum and minimum values in an array.

These two functions are similar, each passes through the array and keeps track of which element is the extreme value (either maximum or minimum). The function does not return the value of the element which is the extreme value but rather the index of the element. It is often better to where a value is in an array than to know the value itself.

  int max_index( int list[], int length )
  {
    int mxindex = 0;
    int max = list[mxindex]; // assume first element is max

    // now go through the rest of the array
    for( int i = 1; i < length; i++ )
      if( list[i] > max )
      {
        max = list[i]
        mxindex = i;
      }

    return mxindex;
  }

  int min_index( int list[], int length )
  {
    int mnindex = 0;
    int min = list[mnindex]; // assume first element is min

    // now go through the rest of the array
      for( int i = 1; i < length; i++ )
      if( list[i] < min )
      {
        min = list[i]
        mnindex = i;
      }

    return mnindex;
  }

Finding a particular element.

This routine is one of the most useful in any programmer's repetoire. The function searches through an array and locates the index of a given value. The function returns the index of the element containing the value. After this function is called, the calling code needs to examine the index which the function returns. If that index is -1 then this signals that the value was not found in the array. A returned index which is zero or greater indicates that the value was found in the array and gives its position in the array. Firstly, here is the function itself:

  int find( int list[], int length, int search_val )
  {
    for( int i=0; i < length; i++ )
      if( list[i] == search_val )
        return i;  // found search_val at position i

    return -1; // not found
  }

Now, here is a fragment of code which shows how to call this function and how to interpret the integer returned.

  int search_val;

  cout << "What number do you want to find? ";
  cin >> search_val;

  int index = find( list, length, search_val );

  if( index < 0 )
    cout << "Sorry, " << search_val << " was not found." << endl;
  else
    cout << "Found " << list[index] << " at position " << index << endl;

Summary.

Array processing routines are important building blocks for many applications. However, they are not hard to understand and most of them follow a design similar to those shown in the example routines above.

A number of other routines are indicated below, in the Tasks associated with this topic.


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 15 - Array processing routines.

  1. Using a similar structure and logic to the example functions in this topic, write a function which returns the average value of the elements of a floating point array.

    Sample Solution

  2. Suppose we have an array which contains the numerical score of 46 competitors (in say an equestrian event), The officials decide to eliminate all competitors who have a score which is below the average score.

    Write a program which processes the the array of scores so that a value of -999 is assigned to every cell in the array which had a score which was below average.

    Sample Solution

  3. Write a program which fills an integer array with 120 random integers each of which is in the range 1..20.

    The program is then to create another array in which each element is the sum of all the elements of the original array up to and including the current element.

    For example, if the first array contains:

      2 5 17 3 ....
    

    Then the second array should contain:

      2 7 24 28 ....
    

    Sample Solution


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 15 - Array processing routines.

Click here to try this topic's test


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Feedback

I am interested in hearing your views about the TTT System or any of its content. If you would like to offer any comments or suggestions please email me:
Author:
Errol Chopping echopping@csu.edu.au
Lecturer in Computing
Charles Sturt University - Mitchell
Bathurst NSW 2795
Australia.
Last Update: Feb 20, 1996