Pointers Lab

Pointers are often used for array processing.

Write a program that allocates an array large enough to hold a user defined number of integers. Create a pointer and make it point to the array. Once all the integers are entered, the array pointer should be passed to a function that uses the pointer to output the sorted array.

Input Validation: Do not accept negative numbers for integers.

Input Data: User enters number of integers first: (ex: 12)

Then user enters integers: (ex: 75, 81, 45, 32, 89,16, -2, 21, 56, 98, 11, 27, 19)

Reminders: Processing an array can either be done with indexes or pointers. Here is a simple code example using both:

int arr[5] = { 1, 2, 3, 4, 5 };

// Traversal by Index
int sum = 0;
for (int i = 0; i < 5; ++i){
sum += arr[i]; // or sum += *(arr + i);
}

// Traversal by Pointer
int sum = 0;
for (int *ptr = arr; ptr < arr + 5; ++ptr) {
sum += *ptr;
}

*************************************************************

Bonus Option (+3 on next exam) : Add a slideLeft function using pointers that moves the first element in the array to the last index and moves all other elements to the left one index. Disply the array before the slide left and after.

********************************************************************************************

Suggested structure for your program: (a little algorithmic assistance..)

// Name:

// Program Description
#include <iostream>
#include <iomanip>
using namespace std;

// Function prototypes
void display(int *, int);

int main()

{

// Initialize variables
int numInts; // The number of integers
int *intArrayPtr; // To point to an array

// Get the number of integers. Validate the input.

// Allocate an array to hold the integers.
int intArray[numInts];

// Make your pointer point at the array

intArrayPtr = intArray;

// Fill the array with integers. Use a for loop and validate integers. //You can use either the name of the array or the pointer for this //step.

// Display the integers using a pointer.
display(intArrayPtr, numInts);

return 0;

}

//********************************************
// Function display
// This function displays the sorted array
// using iPtr to access the array elements.
// The size parameter holds the number of
// elements in the array.
//********************************************

void display(int *iPtr, int size)
{

// Insert code to display sorted array.

}

Turn-in for lab credit a single document with:

Source Code

Screen Shot(s) with test input.

! You are using a version 4 browser or older. If you are experiencing any problems with scrolling, please reload the page.