#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int getmin(int arr[], int N){
int result = arr[0];
for(int i=1; i<N; i++)
result = min(result,arr[i]);
return result;
}
int getmax(int arr[], int N){
int result = arr[0];
for(int i=1; i<N; i++)
result = max(result,arr[i]);
return result;
}
int main(){
int arr[] = {12,35,165,16,23,5,1};
int N = sizeof(arr) / sizeof (int);
cout<<"Minimum element of array : "<< getmin(arr,N)<<endl;
cout<<"maximam element of array : "<< getmax(arr,N)<<endl;
}
Output:
Minimum element of array: 1
Maximum element of array: 165
Explanation:
Step 1: Function to Find Minimum Element
int getmin(int arr[], int N) {
int result = arr[0]; // Start with the first element
for(int i = 1; i < N; i++) {
result = min(result, arr[i]); // Update result with the smaller of result and arr[i]
}
return result; // Return the smallest value found
}
Parameters:
arr[]
: The array to search.N
: The size of the array.
Logic:
result = arr[0];
: Initializeresult
to the first element of the array.- For Loop: Starting from the second element (
i = 1
), compare each element with the currentresult
using themin
function, which returns the smaller value. - Return: The smallest value found in the array is returned.
Step 2: Function to Find Maximum Element
int getmax(int arr[], int N) {
int result = arr[0]; // Start with the first element
for(int i = 1; i < N; i++) {
result = max(result, arr[i]); // Update result with the larger of result and arr[i]
}
return result; // Return the largest value found
}
Logic:
- Similar to
getmin()
, this function initializesresult
with the first element of the array. - The loop goes through each element, updating
result
with the larger of the two values using themax
function. - Finally, the function returns the largest value found.
Step 3: Main Function
int main() {
int arr[] = {12, 35, 165, 16, 23, 5, 1}; // Array initialization
int N = sizeof(arr) / sizeof(int); // Calculating the number of elements in the array
// Print the minimum element
cout << "Minimum element of array: " << getmin(arr, N) << endl;
// Print the maximum element
cout << "Maximum element of array: " << getmax(arr, N) << endl;
return 0;
}
- Array Declaration:
arr[] = {12, 35, 165, 16, 23, 5, 1};
initializes an array with 7 integer elements. - Array Size:
int N = sizeof(arr) / sizeof(int);
calculates the size of the array by dividing the total memory size of the array (sizeof(arr)
) by the size of one integer (sizeof(int)
). - Finding and Printing the Minimum and Maximum:
- The function
getmin(arr, N)
is called to find the minimum value in the array and print it. - Similarly,
getmax(arr, N)
is called to find and print the maximum value.