Sandro
Sandro

Reputation: 487

How do I store an input value in an array using foreach?

This might be an easy one, but as a beginner I'm currently stuck. I tried the tempArray[i] = inputTemp; but it didn't seem to store the value properly when printing the list. Any ideas?

        foreach (int i in tempArray)
        {
            Console.WriteLine("Enter a value");
            double inputTemp = Convert.ToDouble(Console.ReadLine());
            tempArray[i] = inputTemp;
        }
        // Print out the array
        foreach (double i in tempArray)
        {
            Console.WriteLine(i);
        }

Upvotes: 1

Views: 2074

Answers (4)

Sandro
Sandro

Reputation: 487

Thanks for your replies! Since I'm learning I wanted to compare the for and foreach loops to see if I could achieve the same result. And thought I've missed something in my foreach when tested it. However, from your answers I understand foreach wasn't optimal in this case.

Upvotes: 0

Matthew Kligerman
Matthew Kligerman

Reputation: 344

I agree with @Marlon . If you want a fix with less changes (although his method is better): You can just initialize an index variable, and then use the foreach loop (which iterates through values in the array as opposed to indices)

    //this index variable can track the index being changed
    int index = 0;
    foreach (int i in tempArray)
    {
        Console.WriteLine("Enter a value");
        double inputTemp = Convert.ToDouble(Console.ReadLine());
        tempArray[index] = inputTemp;
        index++;
    }
    // Print out the array
    foreach (double i in tempArray)
    {
        Console.WriteLine(i);
    }

Upvotes: 1

voidengine
voidengine

Reputation: 2579

You need to use a for statement in this case

for (var index = 0; index < tempArray.Length; index++)
{
    Console.WriteLine("Enter a value");
    double inputTemp = Convert.ToDouble(Console.ReadLine());
    tempArray[i] = inputTemp;
}

Foreach statement only serves for iterating over an IEnumerable. It abstracts from the fact that the values are stored in an array and you can't modify the underlying array from it.

Technically, you could do the following, but it goes against the design of the language and I would never recommend it. Notice that the iteration variable item is not used

// Don't use
foreach (var (index, item) in tempArray.Select((x, i) => (i, x)))
{
    tempArray[index] = whatever;
}

Upvotes: 2

Marlon
Marlon

Reputation: 20314

The reason it's not working is because foreach loops through the values in tempArray. Therefore i is not an index but actually a value of tempArray, which is probably 0 in each iteration because the array hasn't been initialized with values yet.

You want to use for instead to make i the array index.

for (int i = 0; i < tempArray.Length; i++)
{
    Console.WriteLine("Enter a value");
    double inputTemp = Convert.ToDouble(Console.ReadLine());
    tempArray[i] = inputTemp;
}

Upvotes: 3

Related Questions