Welcome to Westonci.ca, where your questions are met with accurate answers from a community of experts and enthusiasts. Explore thousands of questions and answers from a knowledgeable community of experts on our user-friendly platform. Join our platform to connect with experts ready to provide precise answers to your questions in different areas.
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;
}
Thank you for your visit. We're committed to providing you with the best information available. Return anytime for more. We hope this was helpful. Please come back whenever you need more information or answers to your queries. Westonci.ca is here to provide the answers you seek. Return often for more expert solutions.