In this article we will learn to implement a C program to swap the contents and indexes in an array. A C program is provided below for swapping the array element with the corresponding array index number.
Given an array with size n and its contents are from 0 to n-1. Swap the index and contents at that index.
i/p: a[0] = 3 a[1] = 2 a[2] = 4 a[3] = 1 a[4] = 0
o/p: a[0] = 4 a[1] = 3 a[2] = 1 a[3] = 0 a[4] = 2
The C program for above problem is as follows:
#include <stdio.h>
#include <conio.h>
int main()
{
int n;
int a[20], res[20];
printf("Enter n: ");
scanf("%d", &n);
printf("Enter array elements: ");
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for(int i = 0; i < n; i++)
{
res[a[i]] = i;
}
for(int i = 0; i < n; i++)
{
printf("%d ", res[i]);
}
getch();
return 0;
}
Input and Output for the above program is as follows:
Enter n: 5
Enter array elements: 3 2 4 1 0
4 3 1 0 2
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Please provide the same in java.. as if i give n as 5 in above program and a[1]=6 while swapping iam getting arraayIndexOutOfBound exception. Pls clarify me. I want to give only 5 elements in input array.
In Java also logic will be same. There is a restriction in the input that you should give in the above program. If n is given as 5, the input can only be between 0 and 4. If you give 5 or 6 and so on, you will exceed the limit of array.
how can i do it using pointers