reverse | Sololearn: Learn to code for FREE!

0

reverse

the question is: Write and test the following function: void reverse(int a[],int n); The function reverses the first n elements of the array. For example, the call reverse(a,5) would transform the array {22,33,44,55,66,77,88,99} into {66,55,44,33,22,77,88,99}. my code is: void reverse(int a[],int n); int main() { int a[8]={22,33,44,55,66,77,88,99}; cout<<"The array is: "<<endl; for(int i=0; i<8; i++) { cout<<a[i]<<","; } reverse(a,5); } void reverse(int a[],int n) { for(int i=0; i<n/2; i++) { swap(a[i],a[n-1-i]); } cout<<"\nAfter reverse(a,5):"; for(int i=0; i<n; i++) { cout<<a[i]<<","; } } why the rest not showing?

4/23/2021 8:58:05 PM

Ramisa Fariha

6 Answers

New Answer

+6

There is nothing to be sorry for, buddy! happy learning ☺️

+4

replace reverse(a,5); with reverse(a,8); Since you are reversing the array you will be needing all the elements of the array and in your case it's 8 elements and not just 5 elements.

+2

Your function does exactly what it is supposed to do. The only problem is that your output loop doesn't output the whole array. It only goes to n, 5 in the example, but should go up to the length of the array, 8.

+1

yes yes sorry got it now

+1

Some helpful advice. 1. Use meaningful variable names. It makes the code easier to read. 2. There is no need to declare the size of the array in a case like this. The compiler can work it out. 3. Use a variable for the array size to avoid problems caused by using literals like you have here. This means if you decide to change the array size you only need to change one value. 4. Write a show array function instead of writing the code twice. 5. Don't try to print the result from inside the reverse function. This makes the code more generic, maintains separation of concerns, and avoids duplication of code. #include <iostream> #include <algorithm> using namespace std; void showarray(int arr[], int len); void reverse(int arr[], int len); int main() { int myarray[] = {22, 33, 44, 55, 66, 77, 88, 99}; int array_size = 8; cout << "The array is: " << endl; showarray(myarray, array_size); reverse(myarray, array_size); cout << "\nAfter reversing:" << endl; showarray(myarray, array_size); return 0; } void showarray(int arr[], int len) { for (int i = 0; i < len; i++) { cout << arr[i] << ", "; } cout << endl; } void reverse(int arr[], int len) { for (int i = 0; i < len / 2; i++) { swap(arr[i], arr[len - 1 - i]); } }

+1

ok thank you