Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

b) Describe how the variables “p” and “list” are related. c) Add a reverse funct

ID: 3881405 • Letter: B

Question

b) Describe how the variables “p” and “list” are related.

        c) Add a reverse function that creates an array and returns a pointer to that array. Test your code in the main function.

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

void printArray(int* const list, int size)
{
for (int i = 0; i < size; i++)
    cout << list[i] << " ";
cout << endl;
}

int main()
{
int list[] = {4, 2, 3, 6, 5, 1};
printArray(list, 6);

int* min = min_element(list, list + 6);
int* max = max_element(list, list + 6);
cout << "The min value is " << *min << " at index "
    << (min - list) << endl;
cout << "The max value is " << *max << " at index "
    << (max - list) << endl;

random_shuffle(list, list + 6);
printArray(list, 6);

sort(list, list + 6);
printArray(list, 6);

int key = 4;
int* p = find(list, list + 6, key);
if (p != list + 6)
    cout << "The value " << *p << " is found at position "
         << (p - list) << endl;
else
    cout << "The value " << *p << " is not found" << endl;

return 0;
}

Explanation / Answer

Hi,

Ans: B. The p is pointer which contains the address of a list where key = 4 is stored.

  Ans C.

#include <iostream>

#include <algorithm>

using namespace std;

void printArray(int* const list, int size)

{

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

cout << list[i] << " ";

cout << endl;

}

// This function returns reverse of an array

int * reverseArray(int* const list, int size)

{

// dynamically allocate memory

int *revArray = new int[size];

int j = 0;

for (int i = size - 1; i >= 0; i--)

{

revArray[j] = list[i];

j++;

}

return revArray;

}

int main()

{

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

printArray(list, 6);

int* min = min_element(list, list + 6);

int* max = max_element(list, list + 6);

cout << "The min value is " << *min << " at index "

<< (min - list) << endl;

cout << "The max value is " << *max << " at index "

<< (max - list) << endl;

random_shuffle(list, list + 6);

printArray(list, 6);

sort(list, list + 6);

printArray(list, 6);

int key = 4;

int* p = find(list, list + 6, key);

if (p != list + 6)

cout << "The value " << *p << " is found at position "

<< (p - list) << endl;

else

cout << "The value " << *p << " is not found" << endl;

cout<<"------------ The reverse list is --------------- ";

int *revList = reverseArray(list, 6);

printArray(revList, 6);

int *revList1 = reverseArray(revList, 6);

printArray(revList1, 6);

return 0;

}