Write a program that prints an average temperatue that is close to Zero

The idea is to get the lowest number that is close to the value zero (irrespective of the negative or positive value) from an array of average temperatures that are supplied like so:

{ 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 }

Solution:
One way is to iterate through an array of numbers and store the lowest number in a temp variable and print it out to a console.

As a side, an Array class provides methods for creating, manipulating, searching arrays which serves as the base class for all arrays in common language runtime typically referred to as CLR. The array data structure contains a contiguous collection of data items that can be accessed by an ordinal index.

I have assigned an arbitrary value of 50 to the temp variable prior to iterating through the array elements, comparing it and assigning the lowest number to the temp variable until it reaches the last element of the array before printing out the number.

public static void GetTemperatureCloseToZero()
        {
            double temp = 50.0; //some arbitrary value
            double diff;
            int target = 0;

            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };

            for (int i = 0; i < arr.Length; i++)
            {
                diff = Math.Abs(Convert.ToDouble(arr[i])) - Convert.ToDouble(target);
                if (diff <= temp)
                {
                    temp = diff;
                }
            }
            Console.WriteLine("The closest value to 0 is: {0}", temp);
            Console.ReadLine();
        }

Alternative Solution:
If you don't want to iterate through the items in an array, you can also use the Sort() method to sort elements in the entire list using the default comparer like so:

       public static void GetTempCloseToZeroSort()
        {
            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };
            List list = new List();

            foreach (var item in arr)
            {
                list.Add(Math.Abs(item));
            }
            list.Sort();
            
            Console.WriteLine("The closest value to 0 is: {0}", list[0]);
            Console.ReadLine();
        }

In both case the code produces the following output:ArrayOut1

I hope this will help those that are just getting into data structures.

Cheers,

Obi

 

This entry was posted in Algorithms & Data Structures. Bookmark the permalink.