Pointer Notation for Array Parms


//  this program shows how pointer notation can be used to
//  pass an array as a parameter

#include <iostream.h>

int sum(int *,int);
void printarr(int[],int);
int main()
{
   int nums[10];
   int *intptr;
   int i;
//  store values in the array
   for (i = 0 ; i < 10 ; i++)
      nums[i] = (i + 1) * 2;

//  print out the array
   printarr(nums,10);
   cout << endl;

//  call sum and then print total
   int total = sum(nums,10);
   cout << "The total value of the array elements is "
                                        << total << endl;
   return 0;
}

//  function to add up all the elements in an array of ints
//  1st parm: the array, 2nd parm: size of the array
int sum(int *arr,int size)
{
   int i;
   int total = 0;
   for (i = 0 ; i < size ; i++)
      total += arr[i];
   return total;
}

//  function to print the elements in an array of ints
//  1st parm: the array, 2nd parm: size of the array
void printarr(int *arr,int size)
{
   int i;
   for (i = 0 ; i < size ; i++)
      cout << *(arr+i) << "   ";
   cout << endl;
}

Output:

2   4   6   8   10   12   14   16   18   20

The total value of the array elements is 110

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2001