Be a Supporter!

C# question regarding arrays

  • 399 Views
  • 4 Replies
New Topic Respond to this Topic
SomeTurtle
SomeTurtle
  • Member since: Dec. 12, 2011
  • Offline.
Forum Stats
Member
Level 01
Blank Slate
C# question regarding arrays 2012-11-02 11:28:58 Reply

So I'm still learning C# basics, I have a good chunk of the core down and a decent understanding thus far. One thing is puzzling me and I would really love some help or even being pushed in the right direction would suffice.

Is there a way to create an array with no defined amount of elements? If not what would I use as an alternative.

The best example I could give is the following:

Let's say I created a simple command prompt program that allowed a user to find the average like so(I'm aware that for this example I probably didn't need to create an array at all, but it was the only example I can think of):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string userInput;
            int numberOfEntries;
            int sumOfEntries = 0;
            int[] userEntries;
            float averageOfEntires;

            Console.WriteLine("How many numbers are there?");
            userInput = Console.ReadLine();
            numberOfEntries = Convert.ToInt16(userInput);
            userEntries = new int[numberOfEntries];

            for (int x = 0; x < numberOfEntries; x++)
            {
                Console.WriteLine("Enter Number:");
                userInput = Console.ReadLine();
                userEntries[x] = Convert.ToInt16(userInput);
            }
            foreach (int entry in userEntries)
            {
                sumOfEntries += entry;
            }

            averageOfEntires = sumOfEntries / numberOfEntries;
            Console.WriteLine("The sum is: {0}", sumOfEntries);
            Console.WriteLine("The average is: {0}", averageOfEntires);


            Console.ReadLine();
        }
    }
}

Given the example how could I avoid having to make the user define the amount of entries prior to entering them?

Thanks ahead of time!

SomeTurtle
SomeTurtle
  • Member since: Dec. 12, 2011
  • Offline.
Forum Stats
Member
Level 01
Blank Slate
Response to C# question regarding arrays 2012-11-02 11:42:33 Reply

I did a little more research and it seems I have two options:
1) Using lists
2) Using the ability to resize an array after being established.

Still any insight would help but I think I can take it from here.

Thegluestickman
Thegluestickman
  • Member since: Mar. 16, 2007
  • Offline.
Forum Stats
Member
Level 13
Game Developer
Response to C# question regarding arrays 2012-11-02 16:13:09 Reply

At 11/2/12 11:42 AM, SomeTurtle wrote: I did a little more research and it seems I have two options:
1) Using lists
2) Using the ability to resize an array after being established.

Still any insight would help but I think I can take it from here.

I would definitely use a list for user input. They work like Arrays, but you can add and remove items without any fuss.

For example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string userInput;
            int numberOfEntries;
            int sumOfEntries = 0;
            List<int> userEntries = new List<int>();
            float averageOfEntires;

            Console.WriteLine("How many numbers are there?");
            userInput = Console.ReadLine();
            numberOfEntries = Convert.ToInt16(userInput);

            for (int x = 0; x < numberOfEntries; x++)
            {
                Console.WriteLine("Enter Number:");
                userInput = Console.ReadLine();
                userEntries.Add(Convert.ToInt16(userInput));
                //We just use the add method instead of guessing at how many the user wants
            }
            foreach (int entry in userEntries)
            {
                sumOfEntries += entry;
            }

            averageOfEntires = sumOfEntries / numberOfEntries;
            Console.WriteLine("The sum is: {0}", sumOfEntries);
            Console.WriteLine("The average is: {0}", averageOfEntires);

            Console.ReadLine();
        }
    }
}
Note: I didn't really look at how your code works, I just changed the array instance to a Generic List

To protect the world from devastation.
kidd25 is the best Newgrounder ever.

BBS Signature
deckheadtottie
deckheadtottie
  • Member since: Oct. 21, 2003
  • Offline.
Forum Stats
Supporter
Level 59
Programmer
Response to C# question regarding arrays 2012-11-02 17:20:29 Reply

I would use a List<T>, as you have access to far better methods compared to an array, plus you have the flexibility to add and remove elements as you please and the list will automatically adjust itself. You can even convert your list .ToArray() should you ever need to.

You can access the number of elements the list has by using the Count property, which would be useful to you as you'll need to know how many elements are within the list in order to generate an average.

userEntries.Count;

I also noticed you have a float "averageOfEntires", but then assigning it the result of integer division which will always return an integer.

Finally, you'll now need to use non-deterministic iteration as a List can be of an arbitrary length (you can set bounds- a capacity- but there generally isn't a need). A While or Do...While loop will suit you better to fill you list. Perhaps even checking that an input is valid by using the .TryParse() method available to all primitive data types.


#coys

BBS Signature
SomeTurtle
SomeTurtle
  • Member since: Dec. 12, 2011
  • Offline.
Forum Stats
Member
Level 01
Blank Slate
Response to C# question regarding arrays 2012-11-02 19:24:48 Reply

At 11/2/12 05:20 PM, deckheadtottie wrote: I would use a List<T>, as you have access to far better methods compared to an array, plus you have the flexibility to add and remove elements as you please and the list will automatically adjust itself. You can even convert your list .ToArray() should you ever need to.

You can access the number of elements the list has by using the Count property, which would be useful to you as you'll need to know how many elements are within the list in order to generate an average.

userEntries.Count;

I also noticed you have a float "averageOfEntires", but then assigning it the result of integer division which will always return an integer.

Finally, you'll now need to use non-deterministic iteration as a List can be of an arbitrary length (you can set bounds- a capacity- but there generally isn't a need). A While or Do...While loop will suit you better to fill you list. Perhaps even checking that an input is valid by using the .TryParse() method available to all primitive data types.

Yea the reason was I literally made that little snippet of code in a hurry as I writing the topic to show an example of what I was going for. But thanks for pointing it out because I may do something silly like that in the future and it's good to know. As well thanks for the .TryParse() method, I was always wondering how to check to make sure input was valid(if I entered a letter when a number was requested the program would fail).

Also thanks to the other person who took the time to help! I've since figured out but I always appreciate feedback and learning more.