Home > Enterprise >  i am looking for the right answer for this question, is this correct? [closed]
i am looking for the right answer for this question, is this correct? [closed]

Time:10-06

Write a function void switchEnds(int *array, int size); that is passed the address of the beginning of an array and the size of the array. The function swaps the values in the first and last entries of the array.

#include <iostream>
using namespace std;
void switchEnd(int *array, int size){
    int temp=array[0];
    array[0]=array[size-1];
    array[size-1]=temp;
    
}

int main()
{   const int size=5;
    int array[size]={1,2,3,4,5};
    
    switchEnd(array,size);
    
    for (int c=0;c<5;c  )
    cout<<array[c]<<" ";
}

CodePudding user response:

There are multiple ways to do this. Your way is the straight forward way. But the question reminds me of some questions of c courses, where you should understand pointers.

If this is the case, then an answer like this might be better:

void switchEnd(int *start, int size){
    int *end = start   size - 1;

    int temp=*start
    *start = *end
    *end = temp
}

Be aware that this solution is not the nice way. It is hard to understand and unhandy. So if you want to implement something like this somewhere in your code, use your solution.

Or better:

void switchEnd(int *array, int size){
    std::swap(array[0], array[size-1]);
}
  •  Tags:  
  • c
  • Related