Вы находитесь на странице: 1из 97

1

Chapter #9

Pointers;

Programming challenges;

ONELY 13 PROGRAMS ARE HERE FROM


TH
TONNY GADDIS 9 EDITION.
2

Program 1;

int *arrayAllocator(int numElements){


//first check if argument is 0 or negative
if(numElements <= 0){
//in this case return a null pointer
return nullptr;
}

//otherwise, dynamically allocate memory


//for an array of specified size
int *ptr = new int[numElements];
3

//return the created pointer


return ptr;
}
Program 2;
#include <iostream>

#include <iomanip>

using namespace std;

//function prototypes

void sortArray(double *, int);


4

double getAverage(double *, int);

int main()

//variable to store user input

//for number of tests

int numTests;

//prompt user to enter input then read

cout << "Please enter number of test scores ";

cout << "that will be stored:\n";


5

cin >> numTests;

//dynamically allocate array large enough

double *testScores = new double[numTests];

//read values into array using for loop

for(int counter = 0; counter < numTests;

counter++){

cout << "Test " << counter + 1 << ": ";

//use pointer notation, don't forget


6

//to dereference first

cin >> *(testScores + counter);

//validate input

while(*(testScores + counter) < 0){

//print error message then prompt and read

cout << "ERROR! Negative values not allowed!";

cout << " Enter again!\n";

cin >> *(testScores + counter);

}
7

//sort array

sortArray(testScores, numTests);

//format output

cout << fixed << setprecision(1);

//display contents of array

cout << endl;

cout << "Sorted test scores are: \n";


8

for(int counter = 0; counter < numTests;

counter++){

cout << *(testScores + counter) << " ";

//print message for average

cout << "\n\nAverage of " << numTests << " tests is:

";

cout << getAverage(testScores, numTests);

//return 0 to mark successful termination


9

return 0;

//function to sort array

void sortArray(double *ptr, int arraySize){

//temporary variable to help in swapping

double temp;

//boolean variable that will control when

//array is done sorting

bool swapped = true;


10

while(swapped){

swapped = false;

//loop on all elements

for(int counter = 0; counter < arraySize - 1;

counter++){

//check if following element is greater

//than current element

if(*(ptr+counter) > *(ptr+counter+1)){

//if so, perform swap


11

temp = *(ptr+counter+1);

*(ptr+counter+1) = *(ptr+counter);

*(ptr+counter) = temp;

//and update boolean variable

swapped = true;

} //if ends here

} //for loop ends here

} //while loop ends here

}
12

//function to get average

double getAverage(double *ptr, int arraySize){

//accumulator variable

double total = 0.0;

//loop on all values of array

for(int counter = 0; counter < arraySize; counter++){

total += *(ptr + counter);

}
13

//use typecast to double to

//prevent integer division

return (double)total/arraySize;

Program 3;
#include <iostream>
14

#include <iomanip>

using namespace std;

//function prototypes

void sortArray(double *, int);

double getAverage(double *, int);

int main()

//variable to store user input


15

//for number of tests

int numTests;

//prompt user to enter input then read

cout << "Please enter number of test scores ";

cout << "that will be stored:\n";

cin >> numTests;

//dynamically allocate array large enough

double *testScores = new double[numTests];


16

//read values into array using for loop

for(int counter = 0; counter < numTests;

counter++){

cout << "Test " << counter + 1 << ": ";

//use pointer notation, don't forget

//to dereference first

cin >> *(testScores + counter);

//validate input

while(*(testScores + counter) < 0){


17

//print error message then prompt and read

cout << "ERROR! Negative values not allowed!";

cout << " Enter again!\n";

cin >> *(testScores + counter);

//sort array

sortArray(testScores, numTests);

//format output
18

cout << fixed << setprecision(1);

//display contents of array

cout << endl;

cout << "Sorted test scores are: \n";

for(int counter = 0; counter < numTests;

counter++){

cout << *(testScores + counter) << " ";

//print message for average


19

cout << "\n\nAverage of " << numTests << " tests is:

";

cout << getAverage(testScores, numTests);

//return 0 to mark successful termination

return 0;

//function to sort array

void sortArray(double *ptr, int arraySize){

//temporary variable to help in swapping


20

double temp;

//boolean variable that will control when

//array is done sorting

bool swapped = true;

while(swapped){

swapped = false;

//loop on all elements


21

for(int counter = 0; counter < arraySize - 1;

counter++){

//check if following element is greater

//than current element

if(*(ptr+counter) > *(ptr+counter+1)){

//if so, perform swap

temp = *(ptr+counter+1);

*(ptr+counter+1) = *(ptr+counter);

*(ptr+counter) = temp;

//and update boolean variable


22

swapped = true;

} //if ends here

} //for loop ends here

} //while loop ends here

//function to get average

double getAverage(double *ptr, int arraySize){

//accumulator variable

double total = 0.0;


23

//loop on all values of array, except from

//first one (the lowest score which will be dropped)

for(int counter = 1; counter < arraySize; counter++){

total += *(ptr + counter);

//use typecast to double to

//prevent integer division

return (double)total/arraySize;

}
24

Program 4;
#include <iostream>

#include <iomanip>

#include <string>

using namespace std;

//function prototypes

void sortArray(double *, string *, int);

double getAverage(double *, int);


25

int main()

//variable to store user input

//for number of tests

int numTests;

//prompt user to enter input then read

cout << "Please enter number of test scores ";

cout << "that will be stored:\n";

cin >> numTests;


26

//dynamically allocate array large enough

//for scores and student names

double *testScores = new double[numTests];

string *studentNames = new string[numTests];

//read values into array using for loop

for(int counter = 0; counter < numTests;

counter++){

cout << "Student " << counter + 1 << " name: ";

//use pointer notation, don't forget

//to dereference first


27

cin >> *(studentNames + counter);

cout << "Test score: ";

cin >> *(testScores + counter);

//validate input

while(*(testScores + counter) < 0){

//print error message then prompt and read

cout << "ERROR! Negative values not allowed!";

cout << " Enter again!\n";

cin >> *(testScores + counter);


28

//sort arrays

sortArray(testScores, studentNames, numTests);

//format output

cout << fixed << setprecision(1);

//display contents of array along with names

cout << endl;


29

cout << "Sorted test scores are: \n";

cout << "Name\t\tScore\n";

for(int counter = 0; counter < numTests;

counter++){

cout << *(studentNames + counter) << "\t\t";

cout << *(testScores + counter) << endl;

//print message for average

cout << "\n\nAverage of " << numTests << " tests is:

";
30

cout << getAverage(testScores, numTests);

//return 0 to mark successful termination

return 0;

//function to sort arrays

void sortArray(double *ptr, string *namesPtr, int

arraySize){

//temporary variable to help in swapping

double temp;
31

string tempName;

//boolean variable that will control when

//array is done sorting

bool swapped = true;

while(swapped){

swapped = false;

//loop on all elements


32

for(int counter = 0; counter < arraySize - 1;

counter++){

//check if following element is greater

//than current element

if(*(ptr+counter) > *(ptr+counter+1)){

//if so, perform swap

temp = *(ptr+counter+1);

tempName = *(namesPtr+counter+1);

*(ptr+counter+1) = *(ptr+counter);
33

*(namesPtr+counter+1) =

*(namesPtr+counter);

*(ptr+counter) = temp;

*(namesPtr+counter) = tempName;

//and update boolean variable

swapped = true;

} //if ends here

} //for loop ends here


34

} //while loop ends here

//function to get average

double getAverage(double *ptr, int arraySize){

//accumulator variable

double total = 0.0;

//loop on all values of array, except from

//first one (the lowest score which will be dropped)

for(int counter = 0; counter < arraySize; counter++){


35

total += *(ptr + counter);

//use typecast to double to

//prevent integer division

return (double)total/arraySize;

Program 5;
36

or

int doSomething(int *x, int *y){


//temp has to take value of x,
//so first dereference it
int temp = *x;
37

//modify value of x, using value of y


//so dereference them both
//the asterisk before y is dereference
//operator, the one after y is
//multiplication operator
*x = *y * 10;

//modify value of y, using value


//of temp, but be careful because now
//temp is not a pointer, do not dereference
*y = temp * 10;

//return value of x plus value of y


38

//remember to dereference them first


//dereference operator has precedence
//over the addition operator, so no
//parentheses are required
return *x + *y;
}
Program 6;

// This program is a modification of Program 9-19

// as shown in the book

// This program shows the donations made to the

United Cause
39

// by the employees of CK graphics, Inc. It displays

// the donations in order from lowest to highest

// and in the original order they were received

#include <iostream>

using namespace std;

// Function prototypes

void arrSelectSort(int *[], int);

void showArray(const int [], int);

void showArrPtr(int *[], int);


40

int main()

// variable to hold user choice of number of

donations

int numElements;

cout << "Enter number of donations: ";

cin >> numElements;

//validate input

while(numElements < 1){

cout << "Please enter a number not less than 1: ";


41

cin >> numElements;

// dynamically allocate array of ints

int *donations = new int[numElements];

//read values into array

for(int count = 0; count < numElements; count++){

cout << "Donation " << count+1 << ": ";

cin >> *(donations + count);

}
42

// An array of pointers to int.

int *arrPtr[numElements];

// Each element of arrPtr is a pointer to int. Make

each

// element point to an element in the donations

array.

for (int count = 0; count < numElements; count++ )

arrPtr[count] = &donations[count];
43

// Sort the elements of the array of pointers.

arrSelectSort(arrPtr, numElements);

// Display the donations using the array of pointers.

This

// will display them in sorted order.

cout << "The donations, sorted in ascending order

are: \n";

showArrPtr(arrPtr, numElements);

// Display the donations in their original order.


44

cout << "The donations, in their original order are:

\n";

showArray(donations, numElements);

return 0;

// Definition of function arrSelectSort. *

// This function performs an ascending order selection

sort on *

// arr, which is an array of pointers. Each element of

array *
45

// points to an element of a second array. After the

sort, *

// arr will point to the elements of the second array in

// ascending order. *

void arrSelectSort(int *arr[], int size)

int startScan, minIndex;

int *minElem;
46

for (startScan = 0; startScan < (size - 1); startScan++)

minIndex = startScan;

minElem = arr[startScan];

for(int index = startScan + 1; index < size;

index++)

if(*(arr[index]) < *minElem)

minElem = arr[index];

minIndex = index;
47

arr[minIndex] = arr[startScan];

arr[startScan] = minElem;

// Definition of function showArray. *

// This function displays the contents of arr. size is the

// number of elements. *
48

void showArray(const int arr[], int size)

for (int count = 0; count < size; count++)

cout << arr[count] << " ";

cout << endl;

/* Definition of function showArrPtr. *

This function displays the contents of the array

pointed to *
49

by arr. size is the number of elements*/. *

void showArrPtr(int *arr[], int size)

for (int count = 0; count < size; count++)

cout << *(arr[count]) << " ";

cout << endl;

}
50

Program 7;

/ This program is a modification of Program 9-19

// as shown in the book

// Simply modify arrSelectSort function

// This program shows the donations made to the

United Cause

// by the employees of CK graphics, Inc. It displays

// the donations in order from highest to lowest


51

// and in the original order they were received

#include <iostream>

using namespace std;

// Function prototypes

void arrSelectSort(int *[], int);

void showArray(const int [], int);

void showArrPtr(int *[], int);

int main()

{
52

const int NUM_DONATIONS = 15; // Number of

donations

// An array containing the donation amounts.

int donations[NUM_DONATIONS] = { 5, 100, 5, 25,

10,

5, 25, 5, 5, 100,

10, 15, 10, 5, 10 };

// An array of pointers to int.


53

int *arrPtr[NUM_DONATIONS] = { nullptr, nullptr,

nullptr, nullptr, nullptr,

nullptr, nullptr, nullptr, nullptr,

nullptr,

nullptr, nullptr, nullptr, nullptr,

nullptr };

// Each element of arrPtr is a pointer to int. Make

each

// element point to an element in the donations

array.
54

for (int count = 0; count < NUM_DONATIONS;

count++ )

arrPtr[count] = &donations[count];

// Sort the elements of the array of pointers.

arrSelectSort(arrPtr, NUM_DONATIONS);

// Display the donations using the array of pointers.

This

// will display them in sorted order.


55

cout << "The donations, sorted in descending order

are: \n";

showArrPtr(arrPtr, NUM_DONATIONS);

// Display the donations in their original order.

cout << "The donations, in their original order are:

\n";

showArray(donations, NUM_DONATIONS);

return 0;

}
56

//***********************************************************

****

// Definition of function arrSelectSort. *

// This function performs an ascending order selection

sort on *

// arr, which is an array of pointers. Each element of

array *

// points to an element of a second array. After the

sort, *

// arr will point to the elements of the second array in

*
57

// ascending order. *

//***********************************************************

****

void arrSelectSort(int *arr[], int size)

int startScan, maxIndex;

int *maxElem;

for (startScan = 0; startScan < (size - 1); startScan++)

{
58

maxIndex = startScan;

maxElem = arr[startScan];

for(int index = startScan + 1; index < size;

index++)

if(*(arr[index]) > *maxElem)

maxElem = arr[index];

maxIndex = index;

}
59

arr[maxIndex] = arr[startScan];

arr[startScan] = maxElem;

//**********************************************************

// Definition of function showArray. *

// This function displays the contents of arr. size is the

// number of elements. *

//**********************************************************
60

void showArray(const int arr[], int size)

for (int count = 0; count < size; count++)

cout << arr[count] << " ";

cout << endl;

//***********************************************************

***

// Definition of function showArrPtr. *


61

// This function displays the contents of the array

pointed to *

// by arr. size is the number of elements. *

//***********************************************************

***

void showArrPtr(int *arr[], int size)

for (int count = 0; count < size; count++)

cout << *(arr[count]) << " ";

cout << endl;


62

Program#8

int getMode(int *arr, int numElements){


//keep track of highest number of appearances
//the index, and the mode
int maxAppearances = 0, appearances;
int *mode;

for(int i = 0; i < numElements; i++){


//first reset number of appearances to 0
appearances = 0;

//loop on all elements, to count all appearances


63

//of i-th element from its index until end


for(int j = i; j < numElements; j++){
//compare i-th element with j-th element
if(*(arr + i) == *(arr + j))
//inrecement number of appearances
appearances++;
}

//after counting total number of appearances for


//the i-th element, update mode if necessary
if(appearances > maxAppearances){
//update maximum number of appearances
maxAppearances = appearances;
64

//make mode point to current mode


mode = arr + i;
}
}

//if maximum number of appearances is 1


//there is no mode, return -1
if(maxAppearances == 1)
return -1;

//otherwise, return the mode


return *mode;
65

Program 9;

double getMedian(int *arr, int numElements){


//first check if odd number of elements
//then index of middle element number
//of elements divided by 2
66

if(numElements % 2 == 1){
return *(arr + (numElements / 2));
}
else{
//otherwise
int mid = numElements / 2;

//this will serve as index for the first of


//the median values, the other will be mid - 1
double median = (*(arr + mid) + *(arr + mid - 1)) /
2.0;
return median;
}
67

Program 10;
#include <iostream>

using namespace std;


68

// Function prototype

int* reverseArray(int *, int);

int main()

const int SIZE = 10;

//define a simple array for demonstration

//purposes, that goes from 0 to 9

int arr[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};


69

//print values of this array

cout << "Beginning array:\n";

for(int i = 0; i < SIZE; i++)

cout << *(arr + i) << " ";

//declare a pointer that will get the address

//of the new, reversed array

int *revArr = reverseArray(arr, SIZE);

//print values of new array


70

cout << "\n\nReversed array:\n";

for(int i = 0; i < SIZE; i++)

cout << *(revArr + i) << " ";

cout << endl;

//free up the dynamically allocated memory

delete [] revArr;

//return 0 to mark successful termination

return 0;

}
71

int* reverseArray(int *arr, int SIZE){

//dynamically allocate a new array

int *ptr = new int[SIZE];

//save the values from original array

//into the new one, in reverse order

for(int i = 0; i < SIZE; i++){

//ptr + SIZE - 1 - i will be the last element of new

array

*(ptr + SIZE - 1 - i) = *(arr + i);


72

//return the pointer to new array

return ptr;

Program 11;
73

int* expandArray(int *arr, int SIZE){


//dynamically allocate an array twice the size
int *expPtr = new int[2*SIZE];

//initialize elements of new array


for(int i = 0; i < 2*SIZE; i++){
//first add elements of old array
if(i < SIZE){
*(expPtr + i) = *(arr + i);
}
//all next elements should be 0
else{
*(expPtr + i) = 0;
74

}
}

return expPtr;
}

p
75

int* shiftArray(int *arr, int SIZE){


program12

//dynamically allocate an array twice the size

int *shiftPtr = new int[SIZE+1];

//initialize first element


*shiftPtr = 0;

//initialize other elements of new array


76

for(int i = 1; i <= SIZE; i++){


// be careful to subtract
// one from original array,
// because i index will go
// one step further
*(shiftPtr + i) = *(arr + i - 1);
}

return shiftPtr;
}
Program 13;
#include <iostream>
77

using namespace std;

// Function prototypes

double getAverage(int *, int);

void sortArray(int *, int);

int getMode(int *, int);

double getMedian(int *, int);

int main()

//variable to hold number of students


78

int numStudents;

cout << "Enter number of interviewed students: ";

cin >> numStudents;

//validate input using while loop

while(numStudents <= 0){

cout << "Please enter a number greater than 0: ";

cin >> numStudents;

//dynamically allocate space for the array


79

int *movies = new int[numStudents];

//get number of movies for each student from

//the user

cout << "Number of movies for\n";

for(int i = 0; i < numStudents; i++){

cout << "Student " << i + 1 << ": ";

cin >> *(movies + i);

//validate input using while loop

while(*(movies+i) < 0){


80

cout << "Please enter a nonnegative number: ";

cin >> *(movies+i);

//sort array

sortArray(movies, numStudents);

//display mode

cout << "\n\n The mode: " << getMode(movies,

numStudents);
81

cout << "\n The median: " << getMedian(movies,

numStudents);

cout << "\nThe average: " << getAverage(movies,

numStudents);

//free up the dynamically allocated memory

delete [] movies;

//return 0 to mark successful termination

return 0;

}
82

void sortArray(int *arr, int size)

int startScan, minIndex;

int minElem;

for (startScan = 0; startScan < (size - 1); startScan++)

minIndex = startScan;

minElem = arr[startScan];
83

for(int index = startScan + 1; index < size;

index++)

if(arr[index] < minElem)

minElem = arr[index];

minIndex = index;

arr[minIndex] = arr[startScan];

arr[startScan] = minElem;
84

int getMode(int *arr, int numElements){

//keep track of highest number of appearances

//the index, and the mode

int maxAppearances = 0, appearances;

int *mode;

for(int i = 0; i < numElements; i++){

//first reset number of appearances to 0


85

appearances = 0;

//loop on all elements, to count all appearances

//of i-th element from its index until end

for(int j = i; j < numElements; j++){

//compare i-th element with j-th element

if(*(arr + i) == *(arr + j))

//inrecement number of appearances

appearances++;

}
86

//after counting total number of appearances for

//the i-th element, update mode if necessary

if(appearances > maxAppearances){

//update maximum number of appearances

maxAppearances = appearances;

//make mode point to current mode

mode = arr + i;

}
87

//if maximum number of appearances is 1

//there is no mode, return -1

if(maxAppearances == 1)

return -1;

//otherwise, return the mode

return *mode;

double getMedian(int *arr, int numElements){

//first check if odd number of elements


88

//then index of middle element number

//of elements divided by 2

if(numElements % 2 == 1){

return *(arr + (numElements / 2));

else{

//otherwise

int mid = numElements / 2;

//this will serve as index for the first of

//the median values, the other will be mid - 1


89

double median = (*(arr + mid) + *(arr + mid - 1)) /

2.0;

return median;

double getAverage(int *arr, int numElements){

//variable to get total and average

int total = 0;

double avg;
90

//get total

for(int i = 0; i < numElements; i++)

total += *(arr + i);

//get average

avg = (double)total/numElements;

//return average

return avg;

}
91

Program13;
92
93
94
95
96
97

Вам также может понравиться