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<stdio.h>
int main()
{
	int a[20], min, max;
	int n, i, temp1 = 0, temp2 = 0, pos1 = 0, pos2 = 0;
	printf("Enter the num of elements : ");
	scanf("%d", &n);
	printf("Enter the elements :\n");
	for (i = 0; i<n; i++)
	{
		scanf("%d", &a[i]);
		if (i == 0)
		{
			min = max = a[i];
		}
		if (a[i]<min)
			min = a[i];
		else if (a[i]>max)
			max = a[i];
	}
	printf("\nBiggest element is %d and Smallest elementis %d\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;
	printf("\nArray after interchange of smallest and largest : \n");
	for (i = 0; i<n; i++)
	{
		  printf("\nElement : %d", 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