-4

I need to add values to my array one integer value at a time, via user input.

I don't know how to ask it more clearly, but my goal is to define an integer array in Main(), then pass it to Interactive() where a user is supposed to enter 20 different ints and the program should add them to the array.

It would be tedious to continue defining new arguments for each object (like this):

int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]

because I am filling 20 array objects, surely there is an easier way?

Can someone help?

Here is the code I am working with:

    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = new int[20];
        }

        public static int[] Interactive(int[] args)
        {
            int[] ArrayOne = new int[20];

            Write("\n   Write an integer >>");
            ArrayOne[0] = Convert.ToInt32(ReadLine());

            foreach (int x in ArrayOne)
            {
                if (x != ArrayOne[0])
                    Write("\n   Write another integer");
                ArrayOne[x] = Convert.ToInt32(ReadLine());
                WriteLine("\n   {0}", ArrayOne[x]);
            }

            ReadLine();

            return ArrayOne;
        }

    }
  • 1
    Ask your instructor to check linked duplicates to clarify which of the answer they expect you to copy-paste - one adding elements to pre-allocated array, anther increasing array size. – Alexei Levenkov May 15 '17 at 04:04

2 Answers2

0

Are you looking for this?

 int[] intArray = Interactive(values here);

public static int[] Interactive(int[] args)
    {
     //TODO:
    }
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • hm. I don't know how much that helps. I've already gotten that part figured out I guess. I need to add values to my array one int at a time, via user input. – chickenbiscuit May 15 '17 at 03:33
0

Try using a List. Unlike arrays their size can be dynamically changed.

using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<int> numbers = new List<int>();
        numbers.add(1);
        numbers.add(2);
    }

}