Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ subroutine that given an array of integers, rearranges it in reverse

ID: 3833629 • Letter: W

Question

Write a C++ subroutine that given an array of integers, rearranges it in reversed order. You’ll
need also to design a subroutine to print the array before and after the reversal.
For example, if your solution is a subroutine

void reverse(int a[], int len);  

then you may write the following code to demonstrate your solution:
int main(){  

   const int len1      = 5;  
    int a1[len1];  

   // initialize the array using random numbers or array initializationlist
  
        show(a1, len1);       //print the contents of a1 before the reverse
  
     
   reverse(a1,len1);  
         show(a1, len1);   // print the contents of a1 after the reverse
         

...  

}  

  

In order to test your solution, include in the main() several cases of arrays:
- array of length 1,
- array of length 2,
- array of length 0 (in other words, make sure that your program does not crush when called
with the array of length 0 input),
- array of a small even length larger than 2,
- array of a small odd length larger than 1.


Use indentation and blank lines to make your code more readable. Add comments to explain
the purpose of major code segments.

Explanation / Answer

#include <iostream>
using namespace std;
void reverse(int a[], int len);
void show(int a1[], int len1);
int main(){

const int len1 = 5;
int a1[len1]= {1,2,3,4,5};

// initialize the array using random numbers or array initializationlist
;
show(a1, len1); //print the contents of a1 before the reverse
  

reverse(a1,len1);
show(a1, len1); // print the contents of a1 after the reverse


}
void show(int a1[],int len1){
for(int i=0;i<len1;i++){
cout<<a1[i]<<" ";
}
cout<<endl;
}
void reverse(int a[], int len) {
for(int i=0;i<len/2;i++){
int t = a[i];
a[i]=a[len-1-i];
a[len-1-i] = t;
}
}

Output:

sh-4.2$ g++ -o main *.cpp                                                                                                                                                                                                                                              

sh-4.2$ main                                                                                                                                                                                                                                                           

1 2 3 4 5                                                                                                                                                                                                                                                              

5 4 3 2 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote