# Finding the maximum & minimum element in an array

Reading Time:- 1 min 55 sec

Reading Time:- 1 min 55 sec BY TEJAS

Finding the maximum & minimum element in an array is a very simple program. And this program is asked in many interviews. So the following explanation will help you to understand how to tackle this simple program.

Eg:-
a[ ] = {4, 5, 9, 2, 35, 7, 3, 1}
maximum Element = 35
Minimum Element = 1

## Explanation:

First, we have created an array called `a[]` in which some elements have been passed.  Then the size of an array is stored in the variable `n`.  Then the first element of an array is stored in the variables `min` and `max`.

Then we have created a for loop in which if the value of `a[i]` is greater than the variable `max` then the value of `a[i]` should be stored in the variable `max` & if the value of `a[i]` is less than the variable `min`  So we should store the value of `a[i]` in `min`.

The for loop will continue to be executed until the condition is satisfactory & the smallest and largest element in the whole array will be stored in the variables `min` and `max`.

And after that, we will simply print the values ​​of `min` and `max` variables.

## C Program:

To find the maximum and minimum element in an array.

```                            ```
#include<stdio.h>
int main()
{
int a[] = {20, 2, 5, 9, 23, 7, 54};
int n = sisizeof(a);
int min = a;
int max = a;
for(int i=0; i<n; i++)
{
if(a[i] > max)
max = a[i];

else if(a[i] < min)
min = a[i];
}
printf("Minimum Element in an Array is : %d", min);
printf("Maximum Element in an Array is : %d", max);
}
```
```

## C++ Program:

To find the maximum and minimum element in an array.

```                            ```
#include <iostream>
using namespace std;

int main()
{
int a[] = {20, 2, 5, 9, 23, 7, 54};
int n = sizeof(a) / sizeof(a);
int min = a;
int max = a;
for(int i=0; i<n; i++)
{
if(a[i] > max)
max = a[i];

else if(a[i] < min)
min = a[i];
}
cout << "Minimum Element in an Array is : " << min;
cout << " Maximum Element in an Array is : " << max;
}
```
```

## Java Program:

To find the maximum and minimum element in an array.

```                            ```
public class MinMaxArray {
public static void main(String[] args) {
int[] a = {20, 2, 5, 9, 23, 7, 54};
int n = (int)a.length;
int min = a;
int max = a;
for(int i = 0; i < n; i++) {
if(a[i] > max) {
max = a[i];
} else if(a[i] < min) {
min = a[i];
}
}
System.out.println("Minimum Element in an Array is : " + min);
System.out.print("Maximum Element in an Array is : " + max);
}
}
```
```

## Python Program:

To find the maximum and minimum element in an array.

```                            ```
a = [20, 2, 5, 9, 23, 7, 54]
n = len(a)
min = max = a
for i in range(n):
if a[i] < max:
max = a[i]
elif a[i] < min:
min = a[i]
print("Minimum Element in an Array is : ", min)
print("Maximum Element in an Array is : ", max)
```
```