Home > Enterprise >  C# array issue due to indexing of int
C# array issue due to indexing of int

Time:05-06

I am fairly new to this and trying to learn. I am struggling trying to make a loop to find the max value in an array. I am not sure what I am doing wrong. I have searched everywhere and seen several people do it the way i am but do not know what i am missing…

static void Main(string[] args)
    {
        int[] Numbs = new int[10];
        Numbs[0] = 56;
        Numbs[1] = 77;
        Numbs[2] = 23;
        Numbs[3] = 12;
        Numbs[4] = 88;
        Numbs[5] = 59;
        Numbs[6] = 97;
        Numbs[7] = 33;
        Numbs[8] = 38;
        Numbs[9] = 64;

        string[] Names = new string[10] {"John", "George", "Henry", "Larry", "Bart", "Luke", "Tim",
            "Frank", "Conor", "Joe"};

       

        FindMax(Numbs[9],9);
       
    }

    static int FindMax(int arrayNumbs, int arrayNumbsLength)
    {
        int Greatest = -1;

        for (int Count = 0; Count <= arrayNumbsLength; Count  )
            if (arrayNumbs[Count] > Greatest)
            {
                Console.WriteLine(Count);
                Greatest = arrayNumbs;
                Console.WriteLine(Greatest); 
            }
            return Greatest;

CodePudding user response:

The most basic change would be:

static int FindMax(int[] arrayNumbs)
{

    ...
    for (int Count = 0; Count < arrayNumbs.Length; Count  )
    ...
}

The rest is just fine. There are some ways to make it better, but I'm guessing this is a school assignment and you'll get there eventually.

CodePudding user response:

I can see few things that are issues with your code:

  • Your method defines first parameter as an integer (int arrayNumbs), it should say int[] arrayNumbs since you're passing an array, not a single integer
  • in your function call FindMax(Numbs[9], 9) you pass an integer as the first argument instead of an array (which didn't give you an error since it's how you defined the method, see above). Second argument is a lie, your array's size is 10, not 9 (remember about first element having index [0])
  • Inside your method you want to assign the integer to your variable, not the whole array (which would give you an error). Should say Greatest = arrayNumbs[Count]

CodePudding user response:

You can use a List() instead of the array type. A list is dynamic and will expand automatically. In the example below I create the numbs list and use LINQ to get the max value.

var numbs = new List<int>
{
    56, 77, 23, 12, 88, 59, 97, 33, 38, 65
};

var max = numbs.Max();
  • Related