Discover a world of knowledge at Westonci.ca, where experts and enthusiasts come together to answer your questions. Explore thousands of questions and answers from knowledgeable experts in various fields on our Q&A platform. Get detailed and accurate answers to your questions from a dedicated community of experts on our Q&A platform.
Sagot :
Answer:
The c++ function for reversing an array is given. The function is declared void since it returns no value.
void reverse( int arr[], int len )
{
int temp[len];
for( int k = 0; k < len; k++ )
{
temp[k] = arr[k];
}
for( int k = 0, j = len-1; k < len, j>= 0; k++, j-- )
{
arr[k] = temp[j];
}
}
Explanation:
The reverse function uses another array to reverse the elements of the original array.
An integer array is declared, temp[len], having the same length as the input array.
int temp[len];
To begin with, the elements of the input array are copied in the temp array.
for(int k = 0; k < len; k++ )
{
temp[k] = arr[k];
}
Next, the elements of the input array are given new value.
The temp array, in reverse order, is copied into the input array.
for( int k = 0, j = len-1; k < len, j>= 0; k++, j-- )
{
arr[k] = temp[j];
}
The above for loop makes use of two variables simultaneously.
While the array, arr is proceeding from first element to the next, the array temp begins with the last element and goes down to the previous element.
Now, the input array, arr, contains the elements in reverse order.
The complete program is given.
#include <iostream>
using namespace std;
void reverse( int arr[], int len );
void reverse( int arr[], int len )
{
int temp[len];
for(int k = 0; k < len; k++ )
{
temp[k] = arr[k];
}
for( int k = 0, j = len-1; k < len, j>= 0; k++, j-- )
{
arr[k] = temp[j];
}
}
int main()
{
int len = 5;
int arri[len];
for( int l = 0; l < len; l++ )
{
arri[l] = l;
}
reverse( arri, len );
return 0;
}
Thanks for stopping by. We are committed to providing the best answers for all your questions. See you again soon. We hope this was helpful. Please come back whenever you need more information or answers to your queries. Westonci.ca is committed to providing accurate answers. Come back soon for more trustworthy information.