Question #242808

Write a C++ program to find maximum and minimum element of an array. The minimum element is the lowest value in the array and the maximum is the largest value in the array. Your program should accept N elements, all integer values then the program should display the minimum and maximum element in the array with their corresponding index number.

Expert's answer

#include<iostream>
using namespace std;
void maximum_minimum(int arr[], int size){
	int max =  arr[0];
	int index_max = 0;
	for(int i=0; i<size; i++){
		if(arr[i]>max){
			max = arr[i];
			index_max = i;
		}
	}
	
	int min =  arr[0];
	int index_min = 0;
	for(int i=0; i<size; i++){
		if(arr[i]<min){
			min = arr[i];
			index_min = i;
		}
	}
	cout<<"The maximum element is:  "<<max<<"\nThe maximum element is located at index: "<<index_max<<endl;
	cout<<"The minimum element is:  "<<min<<"\nThe minimum element is located at index: "<<index_min<<endl;
}


int main(){
	cout<<"Enter the number of elements\n";
	int n;
	cin>>n;
	int arr[n];
	cout<<"Enter the elements of the array:\n";
	for(int i=0; i<n; i++){
		cout<<"Element: "<<(i+1)<<endl;
		cin>>arr[i];
	}
	
	maximum_minimum(arr, n);
}
LATEST TUTORIALS
APPROVED BY CLIENTS