Home » .Net

Find smallest element from integer array in C#

In this article we will learn, how to find smallest elements from a list of integers?
Given an integer array and we have to find the smallest element among all array elements.

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.

For example we have list of integers:

18, 13, 23, 12, 27

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.

Consider the example:

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.