Write a method that take in an array of integers, find the maximum and minimum, and return an array containing four elements in the following order.
max integer, max integer index, min integer, min integer index
Solution:
Function:
int* max_min(int *arr){
int max=arr[0],min=arr[0]; // initialises the max and min to first
value of the array.
int *array=new int[4]; // resultant array.
int max_integer_index=0,min_integer_index=0;// indexes are
initialised to 0.
for(int i=1;i<n;i++){
if(arr[i]>max){ // checks if current element is greater than
max.
max=arr[i];
max_integer_index=i;
}
if(arr[i]<min){ // checks if current element is less than
min.
min=arr[i];
min_integer_index=i;
}
}
// initialises the resultant array.
array[0]=max;
array[1]=max_integer_index;
array[2]=min;
array[3]=min_integer_index;
return array; // returns the array.
}
Program implementation:
#include <iostream>
#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
int n; // variable n to decide the size of array.
int* max_min(int *arr){
int max=arr[0],min=arr[0]; // initialises the max and min to first
value of the array.
int *array=new int[4]; // resultant array.
int max_integer_index=0,min_integer_index=0;// indexes are
initialised to 0.
for(int i=1;i<n;i++){
if(arr[i]>max){ // checks if current element is greater than
max.
max=arr[i];
max_integer_index=i;
}
if(arr[i]<min){ // checks if current element is less than
min.
min=arr[i];
min_integer_index=i;
}
}
// initialises the resultant array.
array[0]=max;
array[1]=max_integer_index;
array[2]=min;
array[3]=min_integer_index;
return array; // returns the array.
}
int main()
{
cout<<"Enter n value: ";
cin>>n;
int arr[n];// declares the array.
cout<<n<<endl;
cout<<"Enter n elements for array: ";
// takes input array elements and prints out array elements.
for(int i=0;i<n;i++){
cin>>arr[i];
cout<<arr[i]<<" ";
}
cout<<endl;
int* t=max_min(arr);// function call max_min() method.
// prints the contents of resulatant array returned from the
function.
cout<<"Max element: "<<t[0]<<endl;
cout<<"Max Integer Index: "<<t[1]<<endl;
cout<<"Min element: "<<t[2]<<endl;
cout<<"Min Integer Index: "<<t[3]<<endl;
return 0;
}
Program screenshot:
Program input and output screenshot:
Get Answers For Free
Most questions answered within 1 hours.