C++ Exercises: Reverse a given array of integers and length 5
C++ Basic Algorithm: Exercise-86 with Solution
Reverse Array (Length 5)
Write a C++ program to reverse a given array of integers of length 5.
Sample Solution:
C++ Code :
#include <iostream> // Including the input/output stream library
using namespace std; // Using the standard namespace
// Function that creates and returns a reversed array
int *test(int nums[]) {
// Static array storing the elements of the input array in reverse order
static int r_array[] = {nums[4], nums[3], nums[2], nums[1], nums[0] };
return r_array; // Returning the reversed array
}
// Main function
int main () {
int *p; // Pointer to an integer
int nums[] = {0, 10, 20, 30, 40}; // Define an array nums
int arr_length = sizeof(nums) / sizeof(nums[0]); // Calculate the length of nums
cout << "Original array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << nums[i] << " "; // Output the original array
}
p = test(nums); // Reverse the array and assign it to pointer p
cout << "\nReverse array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << *(p + i) << " "; // Output the reversed array
}
return 0; // Return statement indicating successful termination of the program
}
Sample Output:
Original array: 0 10 20 30 40 Reverse array: 40 30 20 10 0
Visual Presentation:
Flowchart:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-86.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics