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