What are the exact effects of braces in this for-loop?

51 views Asked by At

I have a question about the for loop: This code should add 6 random numbers to 3 different boxes. This code instead puts 21 numbers to each box (*1). I could solve this problem by either removing the braces from the second for-loop(*2) or writing a[i, k] = r.Next(20, 31); in front of the braces(*3). But why?

1

        int[,] a;
        a = new int[7, 3];

        listeBox.Items.Clear();
        listBox1.Items.Clear();
        listBox2.Items.Clear();

        for (int i = 0; i <= a.GetUpperBound(0); i++)    //false
        {

            for (int k = 0; k <= a.GetUpperBound(1); k++) 

            {
                a[i, k] = r.Next(20, 31); 
                listeBox.Items.Add(a[i, 0]);
                listBox1.Items.Add(a[i, 1]);
                listBox2.Items.Add(a[i, 2]);
            }   

        }

2

                for (int k = 0; k <= a.GetUpperBound(1); k++) //correct


                a[i, k] = r.Next(20, 31); 
                listeBox.Items.Add(a[i, 0]);
                listBox1.Items.Add(a[i, 1]);
                listBox2.Items.Add(a[i, 2]);

3

             for (int k = 0; k <= a.GetUpperBound(1); k++) //correct

              a[i, k] = r.Next(20, 31); 

            {
                listeBox.Items.Add(a[i, 0]);
                listBox1.Items.Add(a[i, 1]);
                listBox2.Items.Add(a[i, 2]);
            }   
1

There are 1 answers

1
3Dave On BEST ANSWER

This works because, other than the line a[i,k] = r.Next(20,31), none of the other lines inside of your block use k for anything. In the first example,

for (int k = 0; k <= a.GetUpperBound(1); k++) 
{     
    a[i, k] = r.Next(20, 31); 
    listeBox.Items.Add(a[i, 0]);
    listBox1.Items.Add(a[i, 1]);
    listBox2.Items.Add(a[i, 2]);    
}   

The listBox... lines do exactly the same thing each time through the k loop, so you're unnecessarily doing the same thing over and over.

In your second example, the lack of braces means that the loop only executes the line

a[i, k] = r.Next(20, 31); 

This is the same as saying

for (int k = 0; k <= a.GetUpperBound(1); k++) //correct
    a[i, k] = r.Next(20, 31); 

listeBox.Items.Add(a[i, 0]);
listBox1.Items.Add(a[i, 1]);
listBox2.Items.Add(a[i, 2]);

Once the k loop is complete, it moves on to the listBox.Items.Add(...) code.

In the third example, the braces are not attached to the loop, so you're creating a block without any control structure. It's functionally identical to your second example. It can be useful to create blocks in that way in many circumstances but, in your case, it does nothing.