Click here to Skip to main content
15,924,935 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am having trouble getting my head around arrays, collections and lists although some YouTube videos have helped me a lot. How do I use a loop to populate each array element with its index? I have tried using a foreach loop and a for loop, but neither are working. Please see what I have tried below.

Kind regards

What I have tried:

public static int[] PopulateArray(int[] array)
     {

         foreach (int something in array)
         {

             return something;
         }


     }
 }


public static int[] PopulateArray(int[] array)
      {
          for (int i = 0; ; i++)
          {

              return array;
          }
      }
  }
Posted
Updated 16-Jul-17 22:48pm

1 solution

You can't do it with a foreach - it needs to be a for loop:
C#
public static int[] PopulateArray(int[] array)
      {
          for (int i = 0; i < array.Length; i++)
          {
              array[i] = i;
          }
      return array
      }
 
Share this answer
 
Comments
Member 13302374 17-Jul-17 4:57am    
Thank you. I need to get my head around when to use a for loop, and when to use other types. I guess this'll come with experience

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900