-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
  • 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. Commented May 15, 2017 at 4:04

2 Answers 2

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);
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

I originally had a list, but I am required by my instructor to use array. Thanks though!
List uses an Array "under the hood" anyway.
0

Are you looking for this?

 int[] intArray = Interactive(values here);

public static int[] Interactive(int[] args)
    {
     //TODO:
    }

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.