You are here

C# Float Array

Submitted by Asif Nowaj, Last Modified on 2020-05-08

You can declare a single-dimensional array of five floats as shown in the following example:


float[] floatArray = new float[5];

If you want to initialize the values after declaration, you can do that by


floatArray[0]= 3.0f;
floatArray[1]= 3.5F;
floatArray[2]= 4.0f;
floatArray[3]= 4.5F;
floatArray[4]= 5.0F;

You can declare the array along with initialization of values.


float[]floatArray = {3.0f,3.5F,4.0F,4.5F,5.0F};

You can access the value as below:


foreach (float item in floatArray)
{
  Console.Write("{0} ", item);
}

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns and initializes it as below:


float[,] floatArray3 = new float[4, 2] { { 1.0f, 8.0f }, { 1.1f, 8.1f }, { 1.2f, 8.2f }, { 1.3f, 8.3f } };

The following declaration creates an array of three dimensions, 4, 2, and 3.


float[,,] floatArray4 = new float[4, 2, 3]
{
	{
		{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}
	},
	{
		{3.1f, 3.2f, 3.3f}, {4.1f, 4.2f, 4.3f }
	},
	{
		{5.1f, 5.2f, 5.3f}, {6.1f, 6.2f, 6.3f }
	},
	{
		{7.1f, 7.2f, 7.3f}, {8.1f, 8.2f, 8.3f }
	}
};

Complete code example and demo in C# is below:


using System;

namespace FloatArrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            float[] floatArray = new float[5];
            floatArray[0] = 3.0f;
            floatArray[1] = 3.5F;
            floatArray[2] = 4.0f;
            floatArray[3] = 4.5F;
            floatArray[4] = 5.0F;

            float[] floatArray2 = { 1.0f, 1.5F, 2.0F, 2.5F, 3.0F };

            foreach (float item in floatArray)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();

            foreach (float item in floatArray2)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();
            float[,] floatArray3 = new float[4, 2] { { 1.0f, 8.0f }, { 1.1f, 8.1f }, { 1.2f, 8.2f }, { 1.3f, 8.3f } };
            float[,,] floatArray4 = new float[4, 2, 3]
            {
                {
                    {1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}
                },
                {
                    {3.1f, 3.2f, 3.3f}, {4.1f, 4.2f, 4.3f }
                },
                {
                    {5.1f, 5.2f, 5.3f}, {6.1f, 6.2f, 6.3f }
                },
                {
                    {7.1f, 7.2f, 7.3f}, {8.1f, 8.2f, 8.3f }
                }
            };
            Console.ReadKey();
        }
    }
}

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.

https://forum.everyething.com/dotnet-f40/