Min and Max **Programming Exercise**

Write a function that returns both the minimum and maximum number of the given array. For no particular reason.

Example: {1,2,3,4} => {1,4} {-5,10,20,18}=> {-5,20}

Scroll down for the solution of this very easy coding problem.

There is nothing much to explain if you already did the previous “exercises for beginners”. But if this is new for you -> This is the simple algorithm to get the minimum and/or maximum value number in an array.

public class MinMax { public static int[] minMax(int[] lst) { int min = lst[0]; int max = lst[0]; foreach (int num in lst) { if (num > max) { max = num; } if (num < min) { min = num; } } return new int[] {min, max}; } }

The idea is simple. You go through each number in the array and check … is the first number smaller then…? Oh well, we have to start with a number. Lets assume for a moment that the **first number** is the** smaller one**. Then we go to the second one, and check again. Is this(second) number, **smaller then** the **first**? No? Ok lets continue, but if **Yes**? Well will now check the other numbers against this second number. And continue. Every time we find smaller number then the one we check against, we change the numbers with the smaller one. Until we have no more numbers left. And in this way, we find ourselves with the smallest number of the array.

`using System;`

`using System.Linq;`

public static int[] minMax(int[] lst) { return new int[] {lst.Min(), lst.Max()}; }

This second way to solve this problem shows that the array objects have a functions already in the created for us in the Linq library. I hope one they you can make your own library of useful functions like this. Not to use some stupid ancient algorism over and over again :R

And there is also a third(and the most used) way to solve it… Google it 🙂