How do I create a for loop that has a variable end value?

// I want the program for counts to be looping when it is larger than loopCount and stop looping when loopCount is larger than counts.

Is this all you are putting in your loop function?

yes. Is there something I am missing?

Do you mean something like this?
for (int i=loopCount;i<counts,i++ )
int durationMin=8;
int durationSec=60*durationMin;
int counts=durationSec/8;
Serial.print("Runtime (s): ");
Serial.println(i * 8);

You are putting a loop inside another loop.
When your for loop finishes the loop function restarts.

Try something like this:

int loopCount = 0;
int durationMin=8;
int durationSec=60*durationMin;
int counts=durationSec/8;

void setup() {


void loop() {
  if (loopCount < counts) {
    Serial.print("Runtime (s): ");
    Serial.println(loopCount * 8);
    loopCount = loopCount + 1

Thank you for your reply. I have to use a for loop for this part though.

I think you need to explain your requirement.

There are several ways to do what you want, it it seems that only one will satisfy your teacher.

1 Like

What is "it"?

The requirement is to use a for loop for this part. The loop must keep going until loopCount is greater than counts.

Then just put the for loop in your setup function instead of the loop function.

From the reference page:

for (int i = 0; i <= 255; i++) {

The variable i can be initialized from a Global, or the ending value 255 can be a Global (or a variable within the scope of loop{})


When you do this int counts=durationSec/8; you are creating a local variable inside the for loop's body. It is not the same variable as the counts that is used in the for loop's statement.

Here is a demo of your problem and the (obvious) solution tGFP6X - Online C++ Compiler & Debugging Tool -

If it comes to that, you could just leave it in loop(), and use a ‘flag’ to identify the first pass - so the ‘for loop’ only executes once.

I don't see any place where you vary your end value...

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.