C# Program to swap adjacent elements of an array


In this program, You will learn how to swap adjacent elements of an array in C#.


11 12 13 14 15

12 11 14 13 15

Example: How to swap adjacent elements of an array in C#.

using System;
public class Program
{
	public static void Main(string[] args)
	{
		int i, t;
		int[] arr = new int[6];

		Console.Write("Enter six numbers:");
		for (i = 0; i < arr.Length; i++)
		{
			arr[i] = Convert.ToInt32(Console.ReadLine());
		}

		i = 0;
		while (i < arr.Length - 1)
		{
			t = arr[i];
			arr[i] = arr[i + 1];
			arr[i + 1] = t;
			i = i + 2;
		}

		Console.Write("List after swapping:");
		for (i = 0; i < arr.Length; i++)
		{
			Console.Write(arr[i] + " ");
		}
	}
}

Output:

Enter six numbers:10
20
30
40
50
60
List after swapping:20 10 40 30 60 50 

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.