Find smallest element from integer array in C#

Learn, how to find smallest elements from a list of integers? [Last updated : March 19, 2023]

Finding smallest element of an array

To find smallest element, we assume first element as smallest and store it to variable named small. And then compare small to each element of the array; if any element of the array is greater than the small, then we assign that element to small.

And we follow this process till end of the list. At the end of the loop, we will find the smallest element.

Example

For example we have list of integers:

Input:
18, 13, 23, 12, 27

Output:
Initially large = 18;

In first comparison 	small > 13; true ,  Now small becomes  13. 
In second comparison 	small > 23; false	,  Now small is 13.
In third comparison 	small > 12; true ,  Now small becomes  12.
In forth comparison 	small > 27; false , Now small is  12.

C# program to find smallest element of an array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      int i = 0;
      int small = 0;
      //integer array declaration
      int[] arr = new int[5];

      Console.WriteLine("Enter array elements : ");
      //read array elements
      for (i = 0; i < arr.Length; i++) {
        Console.Write("Element[" + (i + 1) + "]: ");
        arr[i] = int.Parse(Console.ReadLine());
      }

      //assign fist element to the 'small' 
      //compare it with other array elements
      small = arr[0];

      for (i = 1; i < arr.Length; i++) {
        //compare if small is greater than of any element of the array
        //assign that element in it.
        if (small > arr[i])
          small = arr[i];
      }

      //finally print the smallest elemeent of the integer array
      Console.WriteLine("Smallest element in array is : " + small);
    }
  }
}

Output

Enter array elements :
Element[1]: 12
Element[2]: 13
Element[3]: 10
Element[4]: 25
Element[5]: 8
Smallest element in array is : 8

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.