C# program to find maximum and minimum element in an array


Set the minimum and maximum element to the first element so that you can compare all the elements.

For maximum.

if(arr[i]>max) {
   max = arr[i];
}

For minimum.

if(arr[i]<min) {
   min = arr[i];
}

You can try to run the following code to find maximum and minimum elements’ position.

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      int[] arr = new int[5] {99, 95, 93, 89, 87};
      int i, max, min, n;
      // size of the array
      n = 5;
      max = arr[0];
      min = arr[0];
      for(i=1; i<n; i++) {
         if(arr[i]>max) {
            max = arr[i];
         }
         if(arr[i]<min) {
            min = arr[i];
         }
      }
      Console.Write("Maximum element = {0}
", max);       Console.Write("Minimum element = {0}

", min);    } }

Output

Maximum element = 99
Minimum element = 87

Updated on: 23-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements