w3resource

C++ Exercises: Reverse a given array of integers and length 5

C++ Basic Algorithm: Exercise-86 with Solution

Write a C++ program to reverse a given array of integers and length 5.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

int *test(int nums[]) {
   static int  r_array[] = {nums[4], nums[3], nums[2], nums[1], nums[0] }; 
    return r_array;
}

int main () {
   // a pointer to an int.
   int *p;
   int nums[] = {0, 10, 20, 30, 40};	
   
   int arr_length = sizeof(nums) / sizeof(nums[0]);
   cout << "Original array: " << endl;   
   for ( int i = 0; i < arr_length; i++ ) {    
      cout << nums[i] << " ";
   }
   
   p = test(nums);
   cout << "\nReverse array: " << endl;
   for ( int i = 0; i < arr_length; i++ ) {
      cout << *(p + i) << " ";
   }

   return 0;
}

Sample Output:

Original array:
0 10 20 30 40
Reverse array:
40 30 20 10 0

Pictorial Presentation:

C++ Basic Algorithm Exercises: Reverse a given array of integers and length 5.

Flowchart:

Flowchart: Reverse a given array of integers and length 5.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to rotate the elements of a given array of integers (length 4 ) in left direction and return the new array.
Next: Write a C++ program to create a new array containing the middle elements from the two given arrays of integers, each length 5.

What is the difficulty level of this exercise?