Josh
Josh

Reputation: 71

How do I determine the highest and lowest integer in C#?

I would like to know how to determine the highest number and the lowest number out of whatever numbers the user inputs. We're supposed to display those after the user enters 99. Everything I found is using arrays, and we've not yet learned those. Please help!

        string input;
        int input2;
        Console.WriteLine("Enter an integer");
        input = Console.ReadLine();
        input2 = Convert.ToInt32(input);


        while (input2 != 99)
        {
            Console.WriteLine("Enter an integer");
            input = Console.ReadLine();
            input2 = Convert.ToInt32(input);
        }

Upvotes: 1

Views: 2732

Answers (4)

Ricibob
Ricibob

Reputation: 7705

You need some variable to record the max and min (what values should you initialize these to?). On each user input/loop iteration you should compare user input to the current values of these variables and update them if necessary (there are several ways to do that - some more verbose than others). You need to decide (check spec) how to handle 99 eg does that count as min or max?

Upvotes: 0

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

int min = int.Max;
int max = int.Min;

// ...

while (input2 != 99) {
    // ...
    min = Math.Min(min, input2);
    max = Math.Max(max, input2);
}

// At this point, min and max contain the desired result.

There are couple of edge cases here, for example what if user enters 99 right away or she enters only int.Max for min (or int.Min for max), but I'll let you handle that...

Upvotes: -3

Loman
Loman

Reputation: 1019

If you are storing the integers in a list you can use the linq extension methods .Min() to return lowest integer and .Max() to return highest integer.

Upvotes: 0

dtb
dtb

Reputation: 217263

The idea of imperative programming is to give a sequence of statements (an algorithm) that mutate state (a set of variables) until it contains the desired result.

For example, your program changes the contents of the variables input and input2 until input2 contains the value 99.

To find the highest and lowest integer, define two variables, highest and lowest. Change their contents in the while loop such that, after each iteration, they contain the highest and lowest integer respectively, taking the current input value into account.

Upvotes: 5

Related Questions