Where am I going wrong in my loop structure?

I’m trying to make this if statement repeat, but each time it fails. I tried using a while statement instead, that didn’t even run? I’m not sure why only if statements work in my programs and just where I’m generally going wrong.

int r = 0;

int g = 0;

int b = 0;

float timer = 0;

void setup(){

size(800, 800); // size of the project window

};

void draw(){

background(r, g, b);

if(timer < 255){

r = r + 5;

g = g + 2;

b = b + 10;

timer = timer + 0.01;

}

//if the timer is 255/ for each moment timer is less than 255, add 5 to integer r,

//2 to integer b, and 10 to integer b.

//once the integer called timer is greater than 255, this function will end.

//But once the timer is greater than 255, this function will run which will set it back to zero, and the previous function will start again.

};

failing while program

int r = 0;

int g = 0;

int b = 0;

float timer = 0;

void setup(){

size(800, 800); // size of the project window

};

void draw(){

while(timer < 355) {

background(r, g, b);

timer = timer + 0.01;

r= r + 10;

g = g + 3;

b = b + 8;

if(timer > 355){ r = 0; g = 0; b = 0; timer = 0;}

};

here is your first program but running on and on in a loop, repeating the colors


int r = 0;
int g = 0;
int b = 0;

float timer = 0;

void setup() {
  size(800, 800); // size of the project window
}

void draw() {
  background(r, g, b);

  if (timer < 255) {
    r = r + 5;
    g = g + 2;
    b = b + 10;

    timer = timer + 1;
  } else {
    timer = 0;
    r = 0;
    g = 0;
    b = 0;
  }

  //if the timer is 255/ for each moment timer is less than 255, add 5 to integer r,
  //2 to integer b, and 10 to integer b.
  //once the integer called timer is greater than 255, this function will end.
  //But once the timer is greater than 255, this function will run which will set it back to zero, and the previous function will start again.
}

The program with While won’t run as you expect, because draw() doesn’t update the screen throughout but only once at its end. Therefore you won’t see changes in the while-loop but only at the end of draw().


// failing while program

int r = 0;
int g = 0;
int b = 0;

float timer = 0;

void setup() {
  size(800, 800); // size of the project window
}

void draw() {

  background(r, g, b);

  while (timer < 355) {

    background(r, g, b);

    timer = timer + 0.01;

    r= r + 10;
    g = g + 3;
    b = b + 8;
  }

  if (timer > 355) { 
    r = 0; 
    g = 0; 
    b = 0; 
    timer = 0;
  }
}

Warm regards,

Chrisir

1 Like