Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Arrays. 3 Comments on C program to swap the contents and indexes in an array
2.8
(5)

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


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


 

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

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

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.

3 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

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

Leave a Reply

Your email address will not be published. Required fields are marked *