Search code examples
c#arraysliterate-programming

C# IF/Else Array


I am trying to create a simple array example in C# that iterates through the array and only shows values that are greater or equal to 2, but less than 4.

In the if statement I am not sure how best to formulate a two part statement within the iteration function. This is the example I have, which obviously doesnt do anything: else if (array[i] >= 2 array[i] <4)

The full code I am trying to create:

int[] array = new int[5];

            array[0] = 1;
            array[1] = 2;
            array[2] = 3;
            array[3] = 4;
            array[4] = 5;

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] >= 4)
                {
                    Console.WriteLine(array[i]);
                }
                else if (array[i] >= 2 array[i] <4)
                {
                    Console.WriteLine(array[i]);
                }
                else
                {}

            }
            Console.ReadKey();

Looking for suggestions on how best to create this function.


Solution

  • You can do it in one statement:

    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] >= 2 && array[i] < 4)
        {
            Console.WriteLine(array[i]);
        }
    }