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
Release: 2024-12-27 07:09:14
Original
319 people have browsed it

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}");
Copy after login

Output:

Maximum Value: 7
Index of Maximum Value: 3
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template