lightsout22
lightsout22

Reputation: 37

Adding items to an array using a foreach loop in C#

I am trying to do a homework assignment that requires using a foreach loop to add items to an array. I did it using a for loop but cannot figure it out with a foreach loop.

Here is what I need, just in a foreach loop instead.

for (int i = 0; i < 5; i++)
        {
            Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  studentName[i]);
            studentScore[i] = Convert.ToInt32(Console.ReadLine());
            counter = i + 1;
            accumulator += studentScore[i];
        }

Sorry if this has been asked but I could not find an answer that helped me.

Upvotes: 0

Views: 21162

Answers (4)

ThatGuy
ThatGuy

Reputation: 129

Using spans, you are able to get reference vars with the enumerator provided like this: foreach (ref var el in span) {...}. Because they are refs, you are able to modify the values in the array.

Not recommended since foreach loops in pretty much any language generally have zero intent for modifications. Enumerators and iterators in some languages, including C#, don't allow modifications to collections like using Add or Remove methods.

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

Perhaps you meant something like this:

var studentScores = new List<int>();
foreach (var student in studentName)   // note: collections really should be named plural
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student);
    studentScores.Add(Convert.ToInt32(Console.ReadLine()));
    accumulator += studentScores.Last();
}

If you must use an array, then something like this:

var studentScores = new int[studentName.Length];    // Do not hardcode the lengths
var idx = 0;
foreach (var student in studentName)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student);
    studentScores[idx] = Convert.ToInt32(Console.ReadLine());
    accumulator += studentScores[idx++];
}

Upvotes: 0

mehrandvd
mehrandvd

Reputation: 9116

You should have a class like:

class Student
{
    public string Name {get; set; }
    public int Score {get; set; }
}

and a foreach like:

var counter = 0;

foreach (student in studentsArray)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student.Name);
    student.Score = Convert.ToInt32(Console.ReadLine());
    counter++;
    accumulator += student.Score;
}

Upvotes: 2

Praveen Paulose
Praveen Paulose

Reputation: 5771

You could loop through the names array using a foreach loop and read the scores as shown below

foreach(string name in studentName)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ", name);
    studentScore[counter] = Convert.ToInt32(Console.ReadLine());                
    accumulator += studentScore[counter];
    counter++;
}

Console.WriteLine(accumulator);
Console.ReadLine();

Upvotes: 1

Related Questions