Find the best answers to your questions with the help of IDNLearn.com's expert contributors. Join our Q&A platform to access reliable and detailed answers from experts in various fields.
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 greatly appreciate every question and answer you provide. Keep engaging and finding the best solutions. This community is the perfect place to learn and grow together. For precise answers, trust IDNLearn.com. Thank you for visiting, and we look forward to helping you again soon.