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 */
#include <iostream>
using namespace std;
int main() 
{
	int a[20], min, max;
	int n, i, temp1 = 0, temp2 = 0, pos1 = 0, pos2 = 0;
	cout << "Enter the num of elements : ";
	cin >> n;
	cout << "Enter the elements :\n";
	for (i = 0; i<n; i++)
	{
		cin >> a[i];
		if (i == 0)
		{
			min = max = a[i];
		}
		if (a[i]<min)
			min = a[i];
		else if (a[i]>max)
			max = a[i];
	}
	cout << "\nBiggest element is "<<max<<" and Smallest elementis "<<min<<"\n ";

	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;
	cout << "\nArray after interchange of smallest and largest : \n";
	for (i = 0; i<n; i++)
	{
		cout << "\nElement : "<< a[i];
	}
    return 0;
}

Output :
Enter the num of elements : 5
Enter the elements :
10
20
30
40
50

Biggest element is 50 and Smallest elementis 10

Array after interchange of smallest and largest :

Element : 50
Element : 20
Element : 30
Element : 40
Element : 10



Leave a comment