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

CsharpProgrammingServer Side Programming

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}\n", max);
      Console.Write("Minimum element = {0}\n\n", min);
   }
}

Output

Maximum element = 99
Minimum element = 87
raja
Published on 17-Sep-2018 14:13:48
Advertisements