Home » .Net

Find largest element from an integer array in C#

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

To find largest element, we assume first element as largest and store it to variable named large. And then compare large to each element; if value of large is smaller than any element, and then assign that element to large.

Follow this process till end of the list. So that at the end we will get largest element into variable large.

For example we have list of integers:

18, 13, 23, 12, 27

Initially large = 18; In first comparison large < 13; false , Now large is 18. In second comparison large < 23; true , Now large becomes 23. In third comparison large < 12; false , Now large is 23. In forth comparison large < 27; true , Now large becomes 27.

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 large   = 0;
			//array declaration
            int[] arr   = new int[5];
			
			//reading array elements 
            Console.WriteLine("Enter array elements : ");
            for (i = 0; i < arr.Length; i++)
            {
                Console.Write("Element[" + (i + 1) + "]: ");
                arr[i] = int.Parse(Console.ReadLine());
            }

            //assigning first element to the array
			large = arr[0];
			//loop to compare value of large with other elements
            for (i = 1; i < arr.Length; i++)
            {
				//if large is smaller than other element
				//assig that element to the large
                if (large < arr[i])
                    large = arr[i];
            }
			//finally, we will have largest element, printing here
            Console.WriteLine("Largest element in array : " + large);
        }
    }
}

Output

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




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.