Home > Mobile >  Finding odd or even in an C# array
Finding odd or even in an C# array

Time:09-25

I'm supposed to create a method that takes an array and tells if the number is odd or even. I think I'm close to the answer but when I ran the code, it popped up with "Index is outside the bounds of the array". Is there a way to fix that?

private static string OddOrEven(int[] integerArray, string[] numAssign)
{

    foreach (int i in integerArray)
    {
        if (integerArray[i] % 2==0)
        {
            numAssign[i] = " is even";
            string returnValue = integerArray[i]   numAssign[i];
            return returnValue;
        }
        else
        {
            numAssign[i] = " is odd";
            string returnValue = integerArray[i]   numAssign[i];
            return returnValue;
        }
    }
    return "";
}

I'm still new to c# so any help is really appreciated.

CodePudding user response:

Your mistake here is with how foreach works. I'll provide a different example to help you understand:

List<Person> people = GetPeople();
foreach (Person p in people)
{
    Console.WriteLine(p.Name);
}

As you can see, the variable in the foreach actually receives each item, not its index. It's just that you have a list of int so it's not so obvious for you.

It seems like you want a regular for loop:

for(int i = 0; i < integerArray.Length;   i)
{
    if (integerArray[i] % 2==0)
    {
        numAssign[i] = " is even";
        string returnValue = integerArray[i]   numAssign[i];
        return returnValue;
    }
    else
    {
        numAssign[i] = " is odd";
        string returnValue = integerArray[i]   numAssign[i];
        return returnValue;
    }
}

The next curious thing is your return returnValue; - the if statement can only ever enter one or the other, so it will always return a string for the first item only. It won't go on to the second, third, fourth, etc. item as it has already left the method before the loop has a chance to move on to the next value.


Speculation

I expect you want an array of results like this:

private static string[] OddOrEven(int[] integerArray)
{
    string[] resultValues = new string[integerArray.Length];
    for (int i = 0; i < integerArray.Length;   i)
    {
        if (integerArray[i] % 2==0)
        {
            string numAssign = " is even";
            resultValues[i] = integerArray[i]   numAssign;
        }
        else
        {
            string numAssign = " is odd";
            resultValues[i] = integerArray[i]   numAssign;
        }
    }
    return resultValues;
}

Note that I've removed the numAssign incoming array from the method parameters, and now just build it within the method itself.

This would produce a result like this.

  • Related