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.
Home » Programming » C Programming » Programs » Arrays » C program to swap the contents and indexes in an array
Suryateja Pericherla 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

 

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?


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


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 *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory