Printing Arrays

sam500

New member
Joined
Feb 14, 2020
Messages
1
Programming Experience
Beginner
My form has a text box and buttons. The user can enter a number then hit the add button and keep doing that as many times as they want. Then when the Display button is clicked I want to show all of the numbers they entered in the box sorted. My code runs fine but its printing a bunch of zeros and then the numbers I entered and I can't figure out why.
Inside of my Windows Form I have an array declared of size 20.

C#:
int[] numberArray = new int[20];

Then inside of an event handler for a button I'm trying to display the numbers:
C#:
private void btnDisplay_Click(object sender, EventArgs e)
            {
                Array.Sort(numberArray);
                string item= "";
                for (int i = 0; i < numberArray.Length; i++)
                    items+= scoreArray[i];
                MessageBox.Show(items, "Sorted numbers");
                txtScore.Focus();
            }

I'm guessing the extra zeros are because my array is of size 20 but I just want the numbers the user enters printed. I'm having trouble figuring out what I'm doing wrong. Can someone please help me out?
 
You must know how many numbers were entered, so you can sort just the part of the array that was filled with this overload that takes starting index and the number of elements in the range to sort: Array.Sort Method (System)
Similar, you must only output the part of the array that was filled with your for loop.
 
Should you be using an array at all? If this is an assignment, which I think it may be, then you will have to do as they require. Otherwise, you can use a List<int> and then it will only contain the values that you actually add. You could even use a BlockingCollection<int> and specify a maximum size.
 
Back
Top Bottom