I am trying to write code that does what the following C++ code does but without
ID: 3784770 • Letter: I
Question
I am trying to write code that does what the following C++ code does but without indexing:
void shift(int values[], int size) {
int temp = values[size - 1]
int temp1;
for (int i = 0; i < size; i++) {
temp1 = values[i];
values[i] = temp;
temp = temp1;
}
}
If the array for example was 0,1,2,3,4 the function should make the array 4,0,1,2,3 but the code below makes it 4,0,1,3,2
I need help fixing the code. DO NOT CHANGE HOW THE FOR LOOP IS WRITTEN! If you change it to for (int i = 0; i < n; ++i) I WILL MARK IT WRONG. I need to use pointers and traversal by pointers.
void slideRight(int arr[], int n){
int *temp = arr + (n - 1);
int temp1 = 0;
for ( int *ptr = arr; ptr < arr + n; ++ptr) {
temp1 = *(arr + *ptr);
*(arr + *ptr) = *temp;
*temp = temp1;
}
}
Explanation / Answer
New version:
void shift(int values[], int size) {
int temp = *(values + size - 1)
int temp1;
for (int *ptr = values; ptr < values + size; ++ptr) {
temp1 = *ptr;
*ptr = temp;
temp = temp1;
}
}
Old version:
To remove indexing we need to replace a[x] with *(a+x).
So values[i] becomes *(values+i) and values[size - 1] becomes *(values + size - 1).
void shift(int values[], int size) {
int temp = *(values + size - 1)
int temp1;
for (int i = 0; i < size; i++) {
temp1 = *(values+i);
*(values+i) = temp;
temp = temp1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.