# Problem with for() loops

**URL:** <https://discourse.processing.org/t/problem-with-for-loops/45897>\
**Category:** Beginners\
**Created:** [March 3, 2025, 8:30pm UTC](https://discourse.processing.org/t/problem-with-for-loops/45897 "2025-03-03T20:30:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JALAJ\_0106](https://avatars.discourse-cdn.com/v4/letter/j/b38774/32.png) [@JALAJ\_0106](https://discourse.processing.org/u/JALAJ_0106)\
**Post date:** [March 3, 2025, 8:30pm UTC](https://discourse.processing.org/t/problem-with-for-loops/45897/1 "2025-03-03T20:30:09Z")

</div>

```Processing
int th = 36;
  int tw = 36;
  
  for(int y = 0; y < th - 1; y++)
  {
    for(int x = 0; x < tw - 1; x++)
  {
    
    PVector p1 = normals[x][y]; 
    //works
    PVector p2 = normals[34][y]; 
    // works
    PVector p3 = normals[35][y]; 
    // returns null object?

```

---

<div class="post-metadata">

**Author:** ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)\
**Post date:** [March 4, 2025, 8:04am UTC](https://discourse.processing.org/t/problem-with-for-loops/45897/2 "2025-03-04T08:04:53Z")

</div>

Your end of loop conditions are incorrect because they do not access the last element in the array. Try this

```auto
for(int y = 0; y < th; y++)
{
for(int x = 0; x < tw; x++)
{

```

Also in Java a 2D array is created as a ‘1D array’ of ‘1D arrays’ so your for-loops initialize an array

```auto
normals[y][x];

```

This is not causing a problem in your code because `tb == th` a square 2D array if you want

```auto
normals[x][y];

```

then swap the for loops like this

```auto
{
for(int x = 0; x < tw; x++)
{
for(int y = 0; y < th; y++)

```

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [March 4, 2025, 11:39am UTC](https://discourse.processing.org/t/problem-with-for-loops/45897/3 "2025-03-04T11:39:24Z")

</div>

Hello @JALAJ_0106 ,

I suspect that you may have used the same loop to initialize array.

```auto
  PVector p3 = normals[35][0];  
  // null There is no element 35!      
  println(p3);

```

Example:

```auto
int th = 36;
int tw = 36;

PVector normals[][] = new PVector[tw][th]; // Create a 2D array with `tw` columns and `th` rows

for(int y = 0; y < th - 1; y++) // <36-1 is 0 to 34 
  {
  for(int x = 0; x < tw - 1; x++) // <36-1 is 0 to 34
    {
    normals[y][x] = new PVector(0, 0, 0); // Initialize each element with a new PVector
    }
  }
  
  PVector p2 = normals[34][0];
  println(p2);
  // works
  
  PVector p3 = normals[35][0];  
  // null There is no element 35!      
  println(p3);  

```

Try and replace _th-1_ with _th_ and see what happens.  
print _x_ am _y_ in the loop to examine what you are doing.

`:)`
