Search code examples
c#arraysalgorithmarray-algorithms

How do you make an algorithm that will return the number of elements in an array in C#?


I already have some code that I think is going in the right direction, but need help filling in the gap. Please be aware that I cannot use array.Length here and I actually have to make a algorithm that will perform the same function as array.Length. Here is what I have so far:

    public static int size(int[] S, int n)
    {
        for (int i = 0; i < n; i++)
        {
            (S[i] 
        }
    }

Solution

  • This is a very silly assignment as C# arrays provide their length using the Array.Length property. I think you should make this clear in your delivery.

    However, to stay within the rules try this:

    int[] array = new int[10];
    int count = 0;
    
    // iterate all elements in the array
    foreach(int item in array)
    {
        count++;
    }
    
    // count will equal 10
    return count;