0
int L = 2;
int M = 0;
for (int i = 1; i <= 6; i++)
{
   foreach (char c in ListLines[L]) 
   {
      if(c == 'A')arrayOne[M]++;
      if(c == 'B')arrayTwo[M]++;
      if(c == 'C')arrayThree[M]++;
   }
   L =+ 2; 
   M++; 
}

Hi! I'm learning C# at the moment, and I'm trying to create a for loop for my arrays. All I need to know really is can I create an integer (int M) and use that to define the object in the array? For example, arrayOne[M]? As this will allow me to create a counter for it that will let me create a loop.

2
  • what loop do you want to create? what does M represent? why are you using that instead of the existing loop variable i? what does "same outputs for every object" mean? please show exactly the input for the code, and explain exactly what the output is and how that's different from what you wanted. See stackoverflow.com/help/mcve and stackoverflow.com/help/how-to-ask Commented Nov 29, 2014 at 4:07
  • How about a jagged array int[][] array. So you can access it like array[1][M]++. Commented Nov 29, 2014 at 5:15

1 Answer 1

4

Yes you can use indexing on your arrays without problem, as for why you always get the same output, we would need to see the declarations of your arrays.

But in your case, it will make more sense to use a Dictionary instead of multiple arrays. See: http://csharp.net-informations.com/collection/dictionary.htm

As requested below, here is an example with a Dictionary:

var charDict = new Dictionary<char, int>

for (int i = 1; i <= 6; i++){
    foreach (char c in ListLines[i]) {
            charDict[c]++;
        }
    }    

Note: This does not behave the same way as your code, since I honestly didn't get your code logic.

Sign up to request clarification or add additional context in comments.

3 Comments

An example of using a Dictionary to solve this would make this a good answer.
Hi, thanks for the answer. The work is actually coursework, so I've decided against posting the whole thing- as all I really needed was a pointer in the right direction regarding using an integer inside the brackets as aMarks[M] rather than aMarks[1].
Yes there is nothing wrong with your usages of the array. Also if you are using Visual Studio, or any descent c# compiler, you can consider that if you didn't have an error at compilation, then it's fine (not meaning you can't have exceptions at runtime, but your code syntax is legal).

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.