In: Computer Science
The code is bellow. follow this instructions to edit the code :
lets assume that instead of the maximum and minimum values, you want to find the 2nd largest/smallest. For example, in the numbers 1 to 10, this would return 2 and 9 .you will have to change the "max_min" function accordingly. this has a different puepose than "max_min", so you must give it another name.
code:
#include <stdio.h>
#define N 235
void max_min (int a[], int n, int *max, int *min);
int main()
{
int b[N],i,big,small,n;
printf("Enter the Number of elements in the array\n");
scanf("%d",&n);
printf("Enter %d Numbers: \n",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
max_min(b,n,&big,&small);
printf("Largest %d\n",big);
printf("Smallest %d\n",small);
return 0;
}
void max_min(int a[], int n, int *max, int *min)
{
int i;
*min=*max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>*max)
*max=a[i];
else if(a[i]<*min)
*min=a[i];
}
}
The modified code and the corresponding output are as follows:
#include <stdio.h>
#define N 235
void second_maxmin (int a[], int n, int *max2, int *min2);
int main()
{
int b[N],i,n,big2,small2;
printf("Enter the Number of elements in the array:\n");
scanf("%d",&n);
printf("Enter %d Numbers: \n",n);
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
second_maxmin(b,n,&big2,&small2);//function call
printf("Second Largest: %d\n",big2);
printf("Second Smallest: %d\n",small2);
return 0;
}
void second_maxmin(int a[], int n,int *max2, int *min2)
{
int i,j,temp;
//sorting array in descending order
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if (a[i] < a[j])
{
temp=a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
*min2=a[n-2];// last element a[n-1] will be smallest
*max2=a[1];// first element a[0] will be largest
}
Output: