Instead of 0 3 1 4 2 i am getting 0 3 1 4 3 as output

Take as input N, a number. Take N more inputs and store that in an array. Write a recursive function which inverses the array. Print the values of inverted array

Input Format
Enter a number N and take N more inputs

Constraints
None

Output Format
Display the values of the inverted array in a space separated manner

Sample Input
5
0
2
4
1
3
Sample Output
0 3 1 4 2

My code:
#include
using namespace std;
int main() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int i=0;
while(i<n){
a[a[i]]=i;
i=i+1;
}

for(int i=0;i<n;i++){
	cout<<a[i]<<" ";
}
return 0;

}

@alokkr2111_c44918384e4c5a59 , Hi use 2 array else you r changing the content of original array
Logic: Inverse is Simply swapping the value of the array with the value at that index.

Algo
Create a new Array say narr and original array is arr.
now at the arr[i]th index of narr save the ith value.(previously i is the index and arr[i] is the value bt now arr[i] is the index and i is the value.)
print new array.
here’s the updated code https://ide.codingblocks.com/s/659002

Sample Input
5
0
2
4
1
3
Sample Output
0 3 1 4 2

here it means 0 will be in 0 index
1 in 2
2 in 4
3 in 1
4 in 3

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like