find the largest element in an array in csharp

To find the largest element in an array in C#, you can use a loop to iterate through each element of the array and keep track of the current largest value seen so far. Here's an example:

main.cs
int[] array = { 2, 4, 6, 8, 10 };
int max = array[0]; // set the initial max value to the first element of the array
for (int i = 1; i < array.Length; i++)
{
    if (array[i] > max)
    {
        max = array[i]; // update the max value if a larger element is found
    }
}
Console.WriteLine("The largest element in the array is: " + max);
339 chars
11 lines

In this code, we assume the array has at least one element, so we set the initial max value to the first element of the array. Then we loop through the rest of the elements and update the max value if a larger element is found. Finally, we output the max value to the console.

gistlibby LogSnag