each of them have different number that is dependent on the user's input. how to find the smallest number? I usually use math class library in java with min and max method, what to use in C#? Thanx >.< hehe

Dani AI

Generated

asked how to pick the smallest of five user-entered numbers. Both prior replies are on the right track: suggested a loop and pointed out Math.Min. The most practical choices in C# are (1) use LINQ's Min for brevity, (2) use an explicit loop when the index or custom validation is needed, or (3) use Math.Min for simple pairwise comparisons. The examples below use safer initialization and handle common pitfalls.

Using LINQ (concise; requires System.Linq):

using System.Linq;

int[] values = { x1, x2, x3, x4, x5 };
int min = values.Min();

Enumerable.Min will throw on an empty sequence, so validate input first. See the docs: Enumerable.Min

Explicit loop (fast, gives the index and control over ties/validation):

int[] values = { x1, x2, x3, x4, x5 };
int min = values[0];
int minIndex = 0;
for (int i = 1; i < values.Length; i++)
{
    if (values[i] < min)
    {
        min = values[i];
        minIndex = i;
    }
}

Init from the first element rather than an arbitrary constant (avoid 1000000); alternatively use int.MaxValue if the array might be empty and that case is checked.

Notes:

  • For two values Math.Min is fine; nesting it for many values works but is less readable: Math.Min
  • Validate/parsetext input with int.TryParse to avoid exceptions.
  • With floating-point types, handle NaN explicitly before taking a minimum.
    These approaches cover correctness, readability, and basic input-safety for the scenario described.

Recommended Answers

All 2 Replies

Member Avatar for Member #46692

set up a simple loop.

Put the five numbers into an array, then go through them.


array = {5,7,3,2,3}

int smallest = 1000000;

For i = 0 to 5
if array < smallest Then
smallest = array

If you used the Min and Max methods from Java, then you can use the System.Math.Max and System.Math.Min methods in C#

Otherwise create a sortable array, get the first and last elements.

Hope that helps,
Jerry

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.