Find largest element from an integer array in C#

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

Finding largest element of an array

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.

Example

For example we have list of integers:

Input:
18, 13, 23, 12, 27

Output:
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.

C# program to find largest 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 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

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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