Home > Blockchain >  In C# How to correctly pass an int array to a function
In C# How to correctly pass an int array to a function

Time:11-30

how do I pass an array with an unknown number of integers to a function? Can anybody tell me what I am doing wrong?

I get the following error when trying to run the code:

Error CS1501 No overload for method 'Solution' takes 6 arguments

using System;

namespace IntegerTest
{
    class Program
    {
        public static int Solution(int[] input)
        {
            Array.Sort(input);

            int index = 0;

            // Skip negatives
            while (index < input.Length && input[index] < 1)
                index  ;

            int expected = 1;
            while (index < input.Length)
            {
                if (input[index] > expected)
                    return expected;

                // Skip number and all duplicates
                while (index < input.Length && input[index] == expected)
                    index  ;

                expected  ;
            }

            return expected;
        }

        public static void Main()
        {
            Console.WriteLine(Solution( 1, 3, 6, 4, 1, 2));

        }
    }

}
    

CodePudding user response:

You can either call the function with an array argument (e.g. Solution(new[] {1, 3, 6, 4, 1, 2}), or modify the function signature to take a params argument (int Solution(params int[] input)).

CodePudding user response:

Your method accepts a int[], so create a new int[]

Solution(new int[] {1, 3, 6, 4, 1, 2});

CodePudding user response:

You are passing 6 arguments to a method that takes one. Change your main method to something like this:

    public static void Main()
    {
        int[] arr = { 1, 3, 6, 4, 1, 2};
        Console.WriteLine(Solution(arr));

    }
  • Related