Problem making a wrap around loop with modulo

Hello,

Consider:

  • Writing small and simple functional blocks first to understand every element of code.
  • Using console prints, writing text to canvas, coloring, animating, etc. to visualize and understand code.

I saw “wrap around loop using modulo” and wrote this simple example:

// Simple Wrap Around Loop Using Modulo
// v1.0.0
// GLV 2012-02-16

int [] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; //16 elements 
int offset;

void setup() 
	{
  offset = 5;
  for (int i = 0; i< data.length; i++)
    { 
    int w = (i+offset)%data.length;
    println(i, data[i] , data[w]);
    }
  }

I then modified (write text to canvas, added color, animated, etc. ):

Wrap around loop (enhanced)
// Simple Wrap Around Loop Using Modulo
// v2.0.0
// GLV 2012-02-16

int [] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; //16 elements 
int offset;

void setup() 
	{
  size(700, 100);
  textSize(24);
  }

void draw() 
	{
  background(0);
  
  if (frameCount%30 == 0) offset++;       // increments offset every 30 frames
  if (offset > data.length) offset = 0;
  
  for (int i = 0; i< data.length; i++)
    { 
    int w = (i+offset)%data.length;
    
    // no wrapping
    if(i >= offset) fill(255, 0, 0); else fill(0, 255, 0);    
    text(data[i], i*40 + 40, height/2);    
    
    // wrapping
    if(w >= offset) fill(255, 0, 0); else fill(0, 255, 0);
    text(data[w], i*40 + 40, height/2+30); // wrapping
    
    println(i, data[i] , data[w]);
    }
  }

:slight_smile:

1 Like