Array with for loop exercise in Nyhoff book

This is an exercise in the Nyhoff book. I am trying to figure out how to output to the consul the column position and the row position 5 times. So that it reads like this:

column: random number, row: random number
column: random number, row: random number
column: random number, row: random number
column: random number, row: random number
column: random number, row: random number

Instead of getting the random number in the array, I am getting the array location. How do I access the individual random numbers?

size (150, 200);

int [] columns = new int[5];
int [] rows = new int[5];


for (int i = 0; i < columns.length; i++)
{
  columns [i] = int (random(0, width));
  printArray (columns[i]);
}

for (int j = 0; j < rows.length; j++)
{
  rows [j] = int (random(0, height));
  printArray (rows[j]);
}

for (int k = 0; k < rows.length; k++)
{
  println ("columns: " + columns + "," + "rows: " + rows);
}
1 Like

It sounds like it should be a 2D array (grid) and not two 1D array (list) - see tutorials

see https://www.processing.org/tutorials/arrays/

see https://www.processing.org/tutorials/2darray/

but as a 1D array Sketch it works like this

  • printArray (columns); should be outside the for loops. And it can receive the entire array as a parameter ( columns), not only one slot (columns[i])

  • In the 3rd for-loop: to address one slot within an array, use: columns [k]

Chrisir


size (150, 200);

int [] columns = new int[5];
int [] rows = new int[5];


// define columns  
for (int i = 0; i < columns.length; i++)
{
  columns [i] = int (random(0, width));
}
println("-----------------");
printArray (columns);

// define rows 
for (int j = 0; j < rows.length; j++)
{
  rows [j] = int (random(0, height));
}
println("-----------------");
printArray (rows);


// ------------------------------------------------------------------

// show content
println("-----------------");
for (int k = 0; k < rows.length; k++)
{
  println ("columns: " 
    + columns [k] 
    + ","
    + "rows: "
    + rows [k]);
}
//

Thank you @Chrisir!!

Yes, at one point I thought to try solving this using 2D array approach. However, because this exercise follows their (the Nyhoffs’) chapter on 1D arrays I wanted to make sure I could do that via 1D as theoretically it’s a simpler structure… (though still it kicked my butt…) :slight_smile: :nerd_face:

Thank you again!!

1 Like