Search code examples
c#arraysvariablesmethods

How to assign a new value from Method's Array to the Variable?


My main goal is to create a Method, where it is possible to enter a number, out of which a Method will choose some other numbers (according to the purpose) and combine them in Array.

I need this Array and its value to be flexible, so I decided to create a new variable, that is within the scope for both Container() and Main() methods. Then I assigned a value from Container() to optainer, but it didn't work (foreach doesn't display all numbers from Container(), only the first one). Where is my problem?

        static int[] optainer;

        static void Container()
        {
            uint numb = uint.Parse(Console.ReadLine());
            for (int i = 1000000; i >= 1; i--)
            {
                if (numb % i == 0)
                {
                    optainer = new int[] { i };
                }

            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter num. from 1 to 1 000 000");
            Container();
            foreach (int iw in optainer)
            {
                Console.WriteLine(iw);
            }

            // Expected: few numbers according to the condition; Real result: 1 
        
    ```
   

Solution

  • You have always only one element in optainer, this line is the error optainer = new int[] { i }; you create always a new array with only one item and the last is always 1.

    you can change in this way

    static List<int> optainer = new List<int>();
    
            static void Main(string[] args)
            {
                Console.WriteLine("Enter num. from 1 to 1 000 000");
                Container();
                foreach (int iw in optainer)
                {
                    Console.WriteLine(iw);
                }
            }
    
            static void Container()
            {
                uint numb = uint.Parse(Console.ReadLine());
                for (int i = 1000000; i >= 1; i--)
                {
                    if (numb % i == 0)
                    {
                        optainer.Add(i);
                    }
    
                }
            }