Write in C++ please! Thank you 1. (4 pts) Write a function, order1, which takes
ID: 3887873 • Letter: W
Question
Write in C++ please! Thank you
1. (4 pts) Write a function, order1, which takes as input parameters pointers to 2 ints (call by pointer). Inside the function, make sure that the first parameter is less than the second, and, if they aren’t, swap their values so that outside the function the values will be swapped. This function should return a Boolean value true or false, with true indicating that the values were in order and false indicating that you had to swap them. In your main, call this function with 2 random numbers (between 0 and 51, not including 51). Make sure you print out the values before the function and after the function.
2. (4 pts) Repeat the above function with order2, only use pass by reference to modify the parameters.
Explanation / Answer
#include<iostream>
#include<stdio.h>
using namespace std;
// This is call by pointer
bool swap(int *ptr_x, int *ptr_y)
{
if(*ptr_x < *ptr_y)
return true;
else{
int temp;
temp = *ptr_x;
*ptr_x = *ptr_y;
*ptr_y = temp;
return false;
}
}
// This is call by reference
bool swap2(int &ptr_x, int &ptr_y)
{
if(ptr_x < ptr_y)
return true;
else{
int temp;
temp = ptr_x;
ptr_x = ptr_y;
ptr_y = temp;
return false;
}
}
int main(void)
{
int x=9, y=5;
bool z = swap2(x, y);
std::cout << x << " " << y << std::endl; // Now x is 5 and y is 9
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.