The corresponding element in an array can be written as follows.
The given array is arr[len] whose size is given by integer variable len. We take another integer variable k.
Corresponding element for arr[k] = arr[len-1-k]
This applies for all expressions of k beginning from 0 upto half the size of len, i.e., len/2.
For element, arr[0], the corresponding element is arr[10-1-0] = arr[9].
The above expression is valid if the sum of index of both element and its corresponding element adds upto the index of the last element of the array.
Example: k + (len – 1 - k)
= k + len – 1 - k
= len – 1
= index of the last element of the array
The number of elements that an array can hold is one more than the index of the last element of the array.
Suppose an array of 10 elements is given. The above expression holds true since first element of the array is always written as arr[0] and last element will be written as arr[9] for an array of 10 elements.
This is illustrated below.
The c++ program to display the element and its corresponding element along with their index is shown below.
#include <iostream>
using namespace std;
int main() {
int len=10, arr[len],k;
for(k=0; k<len; k++)
{
// elements are initialized to twice their index
arr[k] = k*2;
}
cout<<"Element "<<" Index "<<"\t"<<" Corresponding "<<" Index"<<endl;
for(k=0; k<len/2; k++)
{
cout<<arr[k]<<"\t"<<"\t"<<"\t"<<k<<"\t"<<"\t"<<"\t"<<arr[len-1-k]<<"\t"<<"\t"<<len-1-k<<endl;
}
}
OUTPUT
Element Index Corresponding Index
0 0 18 9
2 1 16 8
4 2 14 7
6 3 12 6
8 4 10 5
The above program initializes all the elements of the array to twice the value of their corresponding index. Following this, the element, its index, the corresponding element and its index is displayed.
All the above is achieved using for loop. The size of the array and its elements can be changed.
The expression for the corresponding element is thus explained.