In this example we will find out the maximum and minimum values from an int array without Max() an Min() Methods.
You can find more similar examples of programming for this programming language in the site.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Program { static void Main(string[] args) { int[] arr = new int[10] { 10, 25, 5, 75, 80, 450, 85, 90, 120, 10 }; int min, max; //Declare two variables max and min to store maximum and minimum. //Assume first array element as maximum and minimum both, say max = arr[0] and min = arr[0] min = arr[0]; max = arr[0]; // Iterate through array to find maximum and minimum element in array. //Inside loop for each array element check for maximum and minimum. for (int i = 0; i < arr.Length; i++) { //Assign current array element to max, if (arr[i] > max) if(arr[i] > max) { max = arr[i]; } //Assign current array element to min if if (arr[i] < min) if (arr[i] < min) { min = arr[i]; } } //Print Array Elements Console.Write("Array Elements:"); foreach (var item in arr) { Console.Write(item+", "); } Console.WriteLine(); //Print max and min number Console.WriteLine("Maximum element:"+max); Console.WriteLine("Minimum element:" + min); Console.ReadLine(); } } |
Output: