0

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.

9
  • foreach is used with an array or list or anything of that sort. Commented Oct 27, 2015 at 19:51
  • 1
    Not sure what you are trying to do, because you can't change the iteration variable while you are iterating (so @mikeTheLair suggestion won't work if you are using it to input scores). Commented Oct 27, 2015 at 19:52
  • 1
    Perhaps reading the book on how a foreach keyword works. You could also google the MSDN for it to see some examples. Commented Oct 27, 2015 at 19:52
  • 1
    you cant do this with foreach loop. is this really homework? foreach loop is for a simple iterations and also you cant change the elements on iterating array. Commented Oct 27, 2015 at 19:53
  • 3
    I guess you could define int[] studentScore = new int[5]; and then do something like foreach(var i in Enumerable.Range(0,5)), technically you are using a foreach loop, but it would be utterly pointless. Perhaps you meant to loop over studentName? That collection, I assume, is already populated? Commented Oct 27, 2015 at 19:55

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@juharr I assumed its just a part of some code there might be used after this code. But for this code, you're right.
1

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();

1 Comment

Thank you very much. This worked perfectly. I had tried something nearly like this but messed it up a bit.
0

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++];
}

4 Comments

Question says "array", so unless the OP is not using the correct terms, this would not be it.
Somehow I suspect that OP's class has not covered collection classes yet.
@crashmstr: Changing it to an array is trivial. Using a list is better anyway (no need to track indexes). Using a list of objects (instead of two parallel collections) would be the best solution.
@mikeTheLiar: I don't see that as remotely relevant. It's a chance to learn something and questions and answers don't exist solely for the benefit of the OP.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.