C# Program to exchange the smallest and largest number in an array of N integers.

/* C# Program to exchange the smallest and largest number in an array of N integers. */
using System;
public class Demo
{
    public static void Main(string[] args)
    {
        int[] a = new int[20];
        int min = 0, max = 0;
        int n, i, temp1 = 0, temp2 = 0, pos1 = 0, pos2 = 0;
        Console.WriteLine("Enter the num of elements : ");
        n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the elements :");
        for(i = 0;i < n;i++)
        {
            a[i] = Convert.ToInt32(Console.ReadLine());
            if(i == 0)
            {
                min = a[i];
                max = a[i];
            }
            if(a[i] < min)
                min = a[i];
            else if(a[i] > max)
                max = a[i];
        }
        Console.WriteLine("Biggest element is {0} and Smallest elementis {1}\n ", max, min);

        for(i = 0;i < n;i++)
        {
            if(min == a[i])
            {
                pos1 = i;
                break;
            }
        }
        for(i = 0;i < n;i++)
        {
            if(max == a[i])
            {
                pos2 = i;
                break;
            }
        }
        temp1 = a[pos1];
        temp2 = a[pos2];
        a[pos1] = temp2;
        a[pos2] = temp1;
        Console.WriteLine("Array after interchange of smallest and largest : ");
        for(i = 0;i < n;i++)
        {
            Console.WriteLine("\nElement : {0}", a[i]);
        }
        Console.ReadLine();
    }
}

Output :
Enter the num of elements :
5
Enter the elements :
1
2
5
6
7
Biggest element is 7 and Smallest elementis 1

Array after interchange of smallest and largest :

Element : 7

Element : 2

Element : 5

Element : 6

Element : 1



Leave a comment