Programming Fundamentals/Arrays/C Sharp

arrays.cs

edit
// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Sharp_Programming

using System;

public class MainClass
{
    public static void Main(String[] args)
    {
        double[] c;
        double[] f;
        
        c = BuildC(100);
        f = BuildF(212);
        DisplayArray("C", c);
        DisplayArray("F", f);
        FindTemperature(c, f);
    }

    private static double[] BuildC(int size)
    {
        double[] c = new double[size + 1];
        int index;
        double value;
        
        for (index = 0; index <= size; index += 1)
        {
            value = (double) index * 9 / 5 + 32;
            c[index] = value;
        }
        
        return c;
    }

    private static double[] BuildF(int size)
    {
        double[] f = new double[size + 1];
        int index;
        double value;
        
        for (index = 0; index <= size; index += 1)
        {
            value = (double) (index - 32) * 5 / 9;
            f[index] = value;
        }
        
        return f;
    }

    private static void DisplayArray(string name, double[] array)
    {
        int index;
        
        for (index = 0 ; index <= array.Length - 1 ; index += 1)
        {
            Console.WriteLine(name + "[" + index + "] = " + array[index]);
        }
    }

    private static void FindTemperature(double[] c, double[] f)
    {
        int temp;
        int size;
        
        size = Minimum(c.Length, f.Length);
        do
        {
            Console.WriteLine("Enter a temperature between 0 and " + (size - 1));
            temp = Convert.ToInt32(Console.ReadLine());
        } while (temp < 0 || temp > size - 1);
        Console.WriteLine(temp.ToString() + "° Celsius is " + c[temp] + "° Fahrenheit");
        Console.WriteLine(temp.ToString() + "° Fahrenheit is " + f[temp] + "° Celsius");
    }

    private static int Minimum(int value1, int value2)
    {
        int result;
        
        if (value1 < value2)
        {
            result = value1;
        }
        else
        {
            result = value2;
        }
        
        return result;
    }
}

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own C Sharp compiler / interpreter / IDE.

See Also

edit