Get reliable answers to your questions at Westonci.ca, where our knowledgeable community is always ready to help. Connect with professionals ready to provide precise answers to your questions on our comprehensive Q&A platform. Get precise and detailed answers to your questions from a knowledgeable 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;
}
We hope this was helpful. Please come back whenever you need more information or answers to your queries. We appreciate your visit. Our platform is always here to offer accurate and reliable answers. Return anytime. We're glad you chose Westonci.ca. Revisit us for updated answers from our knowledgeable team.