Storing Even Numbers in Array

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
Hi,

I have written a piece of code to attempt storing the first 3 even numbers into an array called EvenNumbers.
Here is my code

C#:
using System;
namespace Sample
{
    class Program
    {
        static void Main()
        {
            int[] EvenNumbers = new int[3];
            Console.WriteLine(EvenNumbers.GetLength(0));
            int counter = 1;
            int i = 0;
            do
            {
                if (counter % 2 == 0)
                {
                    EvenNumbers[i] = counter;
                    i++;
                }
                counter++;
            } while (EvenNumbers[2] == null);   //need help here, I want to say keep doing this loop whilst the last array index is empty
        }
    }
}

How do I say in C# "continuing doing while the last index in the array is empty i.e. EvenNumbers[2] is empty or is null?
 
Why would you use a 'do' loop for this in the first place? There are four types of loops. Use the right one for the situation and that is not a 'do' loop in this case.
 
That said, to answer the question that was asked, what does "empty" mean? It means containing the default value, right? 'null' is the default value for reference types, i.e. classes, but a value type can't be 'null'. All you have to do to find out what an "empty" element of an 'int' array looks like is look at any element of your array immediately after you create it.
 
1). Instead of do-while loop I am now using just the while loop.
2). Empty means default. Default of int is 0. Therefore substituted 0 in the while condition.


C#:
using System;
namespace Sample
{
    class Program
    {
        static void Main()
        {
            int[] EvenNumbers = new int[3];
            int counter = 1;
            int i = 0;
            while(EvenNumbers[2]==0)
            {
                if (counter % 2 == 0)
                {
                    EvenNumbers[i] = counter;
                    i++;
                }
                counter++;
            }
        }
    }
}
 
I was actually hinting at using a 'for' loop like this:
int[] evenNumbers = new int[3];

for (int i = 0; i < evenNumbers.Length; i++)
{
    evenNumbers[i] = 2 * (i + 1);
}

Having looked at your code more closely though, I now see that that is not appropriate. It would work for even numbers or other numbers that can be generated using a formula, e.g. Fibonacci numbers or triangular numbers, but it is unsuitable when you want to test every number to see whether it satisfies a condition, e.g. prime numbers.

In your case, rather than worrying about the value of the last element, I would suggest that you worry about whether the index is valid, i.e.
int[] evenNumbers = new int[3];
int counter = 1;
int i = 0;
while (i < evenNumbers.Length)
{
    if (counter % 2 == 0)
    {
        evenNumbers[i] = counter;
        i++;
    }
    counter++;
}

Like the 'for' loop, that will now work for an array of any length without change. By the way, do you notice any similarities between my two examples? Take a closer look:
C#:
int[] evenNumbers = new int[3];

for ([COLOR="#FF0000"]int i = 0[/COLOR]; [COLOR="#008000"]i < evenNumbers.Length[/COLOR]; [COLOR="#0000FF"]i++[/COLOR])
{
    evenNumbers[i] = 2 * (i + 1);
}
C#:
int[] evenNumbers = new int[3];
int counter = 1;
[COLOR="#FF0000"]int i = 0[/COLOR];
while ([COLOR="#008000"]i < evenNumbers.Length[/COLOR])
{
    if (counter % 2 == 0)
    {
        evenNumbers[i] = counter;
        [COLOR="#0000FF"]i++[/COLOR];
    }
    counter++;
}
It's not necessarily so in other languages, e.g. VB, but in C# and other C-based languages, a 'for' loop is just a specialised 'while' loop.
 
I don't recommend that you do this but, for completeness, I thought that I'd point out that, because a 'for' loop is just a specialised 'while' loop, you could still use a 'for' loop like this:
int[] evenNumbers = new int[3];

for (int counter = 1, i = 0; i < evenNumbers.Length; counter++)
{
    if (counter % 2 == 0)
    {
        evenNumbers[i++] = counter;
    }
}

The 'for' statement has three parts: declaration, Boolean test and action. In a "standard" 'for' loop, you declare a loop counter in the first part, test that that counter has not exceeded a maximum value in the second part and increment the counter in the third part. It doesn't have to be that way though. You can declare multiple variables in the first part, as I have done here. You can then test any Boolean expression you like in the second part. It may or may not involve the loop counter(s) and it may or may not test against a maximum value. The third part can also include multiple actions and they can be anything that makes an assignment, whether that be incrementing the loop counter or not.

Note that, in this case, I've also combined the setting of the element at the current index and the incrementing of the index. Some people don't like doing that because they think it makes the code harder to read and that's a valid point of view. C/C++ developers often like packing as much functionality into as little code as possible and that can make code cryptic. C# developers often like to make readability their priority. Regardless, combining the two actions into one line of code is perfectly valid. In case you're not aware, it's very important that you use a post-increment and not a pre-increment in this case. This would not work:
evenNumbers[++i] = counter;

because that does a pre-increment, i.e. it increments the value of 'i' first and then uses that result in the rest of the code. That's not what we want here. We want to use the value of 'i' in the rest of the code first, then increment it. That's a post-increment:
evenNumbers[i++] = counter;

For interest's sake, that brings up am interesting point regarding the name of the C++ language. That name is used because it is an incremental change to the C language, but many argue that it should have been ++C because you're using the language after the incremental change rather than before.
 
So I learnt few things from your replies to my initial question.
1). A while loop in C# can be represented by a for-loop - as you have mentioned, a for-loop is just a specialised version of a while-loop and vice versa
2). Thank you for pointing out the pre-increment and post-increment (never came across this concept but you have explained it very well and I understood).
3). Didn't know you can wrap multiple variables inside the declaration part of a for loop and specify only one of the variable in the Boolean test. I tried this out and it works really well. I actually like it although I know you said you do not recommend it :)

Thank you!
 

Latest posts

Back
Top Bottom