Search This Blog

Monday, May 9, 2011

C++ Program: Array Function


Write a function 

void switchEnds(int *array, int size); 

that is passed the address of the beginning of an array and the size of the array. The function swaps the values in the first and last entries of the array. 

Here is the code to switch two integers: 

void exchange(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;


Demonstrate the function with a driver program. 

Here is what it could look like (depending on integers you write in the code): (Click to enlarge)
Here's the code: 
// Kim Pestana, Chapt. 10 Pointers
// Write a function that is passed the address of the beginning of an array and the size
// of the array. The function swaps the
// values in the first and last entries of the array. Demonstate the funtion with
// a driver program.

#include<iostream>
#include<iomanip>
using namespace std;

// Function prototype
void switchEnds(int ar[], int array_size);

int main()
{
       // define array
       const int TEMPS = 5;
       int temp[TEMPS];

       temp[0] = 32;
       temp[1] = 36;
       temp[2] = 40;
       temp[3] = 45;
       temp[4] = 54;

       switchEnds(temp, TEMPS);
       cout << "Calling the switchEnds function: " << temp[0] << " " << temp[TEMPS-1] << endl;

       system("Pause");
       return 0;
}

// Function switchEnds is to switch values in the first and last array entries
       void switchEnds(int ar[], int array_size)
       {
           int temp = ar[0];
           ar[0] = ar[array_size-1];
           ar[array_size-1] = temp;
       }

No comments:

Post a Comment