C# program to swap min and max element in integer array
To swap the minimum and maximum elements in an integer array in C#, you can find the indices of the minimum and maximum elements, and then perform the swap. Here's an example program that swaps the minimum and maximum elements in an integer array:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
SwapMinAndMax(numbers);
Console.WriteLine("Array after swapping min and max elements:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
public static void SwapMinAndMax(int[] nums) {
int minIndex = 0;
int maxIndex = 0;
// Find indices of the minimum and maximum elements
for (int i = 1; i < nums.Length; i++) {
if (nums[i] < nums[minIndex]) {
minIndex = i;
}
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
// Swap the minimum and maximum elements
int temp = nums[minIndex];
nums[minIndex] = nums[maxIndex];
nums[maxIndex] = temp;
}
}
In this program, we have an array of integers called numbers. We use the SwapMinAndMax method to swap the minimum and maximum elements in the array.
The method first finds the indices of the minimum and maximum elements in the array by iterating through the elements. Then, it performs the swap by using a temporary variable.
The program outputs the array after swapping the minimum and maximum elements:
Array after swapping min and max elements:
5 2 8 3 9 1 4 6 7
In this case, the minimum element is 1 and the maximum element is 9. After swapping them, the array is modified accordingly.