Exercise
Function Greatest Value In A Array
Objective
Write a C# function which returns the greatest value stored in an array of real numbers which is specified as parameter:
float[] data={1.5f, 0.7f, 8.0f}
float max = Maximum(data);
Example C# Exercise
Show C# Code
// Importing necessary namespaces
using System;
class Program
{
// Main method to drive the program
public static void Main()
{
// Example array of floating-point numbers
float[] data = { 1.5f, 0.7f, 8.0f };
// Calling the Maximum function to find the greatest value in the array
float max = Maximum(data);
// Display the result
Console.WriteLine("The greatest value in the array is: " + max);
}
// Function to return the greatest value in an array of real numbers
public static float Maximum(float[] arr)
{
// Initialize max to the smallest possible value
float maxValue = arr[0];
// Loop through the array to find the maximum value
for (int i = 1; i < arr.Length; i++)
{
// Update max if a larger value is found
if (arr[i] > maxValue)
{
maxValue = arr[i];
}
}
// Return the largest value found in the array
return maxValue;
}
}
Output
The greatest value in the array is: 8