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

Problem 3: What does the following program print and why? Be sure to explain why

ID: 3838892 • Letter: P

Question

Problem 3:  What does the following program print and why? Be sure to explain why each line of output prints the way it does to get full credit.  

#include <iostream>
using namespace std;

int* minimart(int* a, int* b)
{
if (*a < *b)
return a;
else
return b;
}

void swap1(int* a, int *b)
{
int* temp = a;
a = b;
b = temp;
}

void swap2(int* a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int array[6] = { 5, 3, 4, 17, 22, 19 };

int* ptr = minimart(array, & array[2]);
ptr[1] = 9;
ptr += 2;
*ptr = -1;
*(array+1) = 79;

cout << "diff=" << &array[5] - ptr << endl;

swap1(&array[0], &array[1]);
swap2(array, &array[2]);

for (int i = 0; i < 6; i++)
cout << array[i] << endl;

return( 0 );
}

Explanation / Answer

Hi, I have commented each line.

Please let me know in case of any issue.

#include <iostream>
using namespace std;

// this function returns the minimum between 'a' and 'b'
int* minimart(int* a, int* b)
{
if (*a < *b)
return a;
else
return b;
}

// this function NOT swapping value of a and b
// we are doing local assignment locally
void swap1(int* a, int *b)
{
int* temp = a;
a = b;
b = temp;
}
// tHis function swapping the content of a and b
void swap2(int* a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main()
{
// array areating
int array[6] = { 5, 3, 4, 17, 22, 19 };

// getting the minimum value of array
int* ptr = minimart(array, & array[2]);

// ptr pointing to 3

// ptr[1] means 3rd element of array, because ptr base address is equal to address of second element of array
ptr[1] = 9; // it chabging 3rd element of array, array[2] = 9
ptr += 2; // ptr pointing to 4th element of array (17)
*ptr = -1; // repacing 17 to -1
*(array+1) = 79;// replacing 3(2nd element) to 79

cout << "diff=" << &array[5] - ptr << endl; // &arrar[5] - ptr => address of 5th element - address of 4th element
// because ptr pointing to array[4] , output = 1 (one number of elements)

swap1(&array[0], &array[1]); // calling swapping1 metho, it will not any thing
swap2(array, &array[2]); // calling swap2 method, it swao the value of first element and 3rd element=> 9 - 5 = 4
for (int i = 0; i < 6; i++) // printing the array element
cout << array[i] << endl;
return( 0 );
}

// Output
  
diff=1
4
79
5
9
-1
19

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote