1

I just started out with arrays and it is AMAZING!

One small thing though, how come my for loop isnt printing out the whole index or rather the value of the index one by one, but instead only prints out the last one?

enter image description here

Here is my code if you are having some issues with viewing the image!

namespace Arrays
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int[] numbers = new int[5];


        private void Form1_Load(object sender, EventArgs e)
        {
            numbers[0] = 12;
            numbers[1] = 10;
            numbers[2] = 25;
            numbers[3] = 10;
            numbers[4] = 15;
        }


        private void button1_Click(object sender, EventArgs e)

        {
            for (int i = 0; i < numbers.Length; i++)

            displayArrays.Text = numbers[i].ToString();
        }

    }
}

3 Answers 3

2

Because you are just assigning value each time. Change

displayArrays.Text = numbers[i].ToString();

To

displayArrays.Text += numbers[i].ToString();

Or if separator is needed:

displayArrays.Text += numbers[i].ToString() + ", "; // But need to worry about trailling separator.

If you want the index, then i represents your current index. numbers[i] represents array value at index i.

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

3 Comments

Oh okay! So what I am essentially doing is (+=) adding more values from the array to the index?
@Alexander. Matt displayArrays.Text is another field (or as you call index). If you use simple = then it just assigns new value. += translates into displayArrays.Text = displayArrays.Text + numbers[i].ToString() + ", ";. That is - updating current value.
Oh that makes so much sense now! Thank you! @DovydasSopa
1

Mostly other answers answered what you need, you could simplify a bit with this one liner.

Remove for loop completely and place this logic.

displayArrays.Text = string.Join(",", numbers);

2 Comments

@HariPrasad im actually going to loop through 26.000 lines of text later on so wouldnt I need the for loop then?
Depends on your case, if you just want to display numbers then you don't need any loop. Additionally if you are performing any other logic may be you need it, difficult to comment unless I see complete code.
0

Try this code

for (int i = 0; i < numbers.Length; i++)
        displayArrays.Text += ", " + numbers[i].ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.