How to return all the Elements of an array.

How to return all the Elements of an array.

Hey Guys! I'm just a newbie here, I need help with my code;

How do I return the values in the element? can it be done?
or should I just rewrite my code?. I'll be pleased if you help me thank you.

#include <iostream>


using namespace std;


int swap(int s[4]);

int main(){

int num[5] = {1, 4, 9, 16, 25};

//for(int i = 0; i < 5; i++)
//{
// cout << num[i] << ' ';
//}

cout << endl;

cout << swap(num);

cout << endl;

system("Pause");
return 0;
}

int swap(int s[4])
{
int temp;
int a,b;

a = s[0];//1
b = s[4];//25

temp = a;
a = b;
b = temp;

int final[5] = {a , s[1] , s[2] , s[3] , b};
}

return final[5];


}


the problem lies on the function
1
2
3
4
int swap( int s[] );

int num[5];
cout << swap(num);

is like:
1
2
3
int num[5];
int temp = swap(num);
cout << temp;

In other words, if you get one integer from the function, then that is what you get.

Note that:
1
2
int num[5];
cout << num;

does not print the elements of the array.
You need that:
1
2
3
4
for (int i = 0; i < 5; i++) {
  cout << num[i] << ' ';
}
cout << '\n';



Lets rephrase what you actually want to do:
Modify array by swapping the first and last element.

You could do that with:
std::swap( num[0], num[4] );

If you want a function of your own that manipulates an array, then:
1
2
3
void swap( int* arr, int size );

swap( num, 5 );



Your function, however, does not modify the array, but attempts to create a modified copy.
That is bit different.
1
2
3
4
5
6
void swap( const int* orig, int* result, int size );

int num[5];
int bar[5];
swap( num, bar, 5 );
// display bar 


If you really want to return the new "array", then plain array is not an option.
You need to return a copyable object:
1
2
3
4
5
std::vector<int> swap( const int* orig, int size );

int num[5];
auto bar = swap( num, 5 );
// display bar 

Thank you very much, you made it simple enough
Topic archived. No new replies allowed.