Home >Backend Development >C++ >How to Find the Maximum Value and Its Index in a C# Unsorted Array?

How to Find the Maximum Value and Its Index in a C# Unsorted Array?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 07:09:14258browse

How to Find the Maximum Value and Its Index in a C# Unsorted Array?

Finding the Highest Value and Index in an Unsorted Numeric Array in C#

To determine both the maximum value and its corresponding index in an unsorted numeric array, such as your int[] anArray = { 1, 5, 2, 7 }, you can employ the following approach:

Approach:

  1. Utilize the Max() method from the System.Linq namespace to identify the highest value in the array.
  2. Convert the array to a list using ToList() to access its indexing capabilities.
  3. Use IndexOf() on the converted list to determine the index of the maximum value.

Code:

using System.Linq;

int[] anArray = { 1, 5, 2, 7 };

// Find the maximum value
int maxValue = anArray.Max();

// Find the index of the maximum value
int maxIndex = anArray.ToList().IndexOf(maxValue);

// Display the results
Console.WriteLine($"Maximum Value: {maxValue}");
Console.WriteLine($"Index of Maximum Value: {maxIndex}");

Output:

Maximum Value: 7
Index of Maximum Value: 3

The above is the detailed content of How to Find the Maximum Value and Its Index in a C# Unsorted Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn