-1

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.

JAS
  • 305
  • 3
  • 5
  • 12
  • You have to combine the two results using some logical functions - in this case `AND` which in `C#` is `&&`. – lared Feb 09 '15 at 19:05
  • 1
    Your condition should be `if (array[i] >= 2 && array[i] <4)`. Read about [Conditional logical operators](https://msdn.microsoft.com/en-us/library/aa691310%28v=vs.71%29.aspx) – Habib Feb 09 '15 at 19:06
  • you can save some code by using a `foreach` instead – Jonesopolis Feb 09 '15 at 19:07
  • Not sure why, but the many of these answers have neglected your `array[i] >= 4` comparison. Be careful if taking the code directly – Bob2Chiv Feb 09 '15 at 19:30
  • Because while the code shows an >= 4 comparison, the text of the question does not. – Steve Mitcham Feb 09 '15 at 19:32

4 Answers4

5

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]);
    }
}
itsme86
  • 19,266
  • 4
  • 41
  • 57
4

LINQ is your friend

var selected = array.Where(x => x>= 2 && x < 4);

and if you really want a one liner with the console IO

array.Where(x => x>= 2 && x < 4).ToList().Foreach(x=>Console.WriteLine(x));
pm100
  • 48,078
  • 23
  • 82
  • 145
1

Use the conditonal AND operator (&&)

else if (array[i] >= 2 && array[i] <4)
Cyral
  • 13,999
  • 6
  • 50
  • 90
0

As the other answers have mentioned, you are missing the conditional AND operator (&&).

Using it would change your

else if (array[i] >= 2 array[i] <4)

to

else if(array[i] >= 2 && array[i] < 4)

But, you can do one better with your current code. Since you are doing the same operation in your if and in your else if, and you are comparing against int with a continuous comparison (ie: 2,3,4 etc return true). You can further simplify it to this:

for (int i = 0; i < array.Length; i++)
{
    if(array[i] >= 2)
    {
         Console.WriteLine(array[i]);
    }
}
Bob2Chiv
  • 1,858
  • 2
  • 19
  • 29