for loop

Hello forum, i'm new here, also to arduino and not a programmer.
it's first attempt to microcontroller that finally going somewhere. thanks to arduino i don't have to learn assembler.

Can anyone explain to me why

for(i = 0; i < 10; i++) { ...

works, but

for(i = 0; i == 10; i++) { ...

won't?
thanks in advance.

We'd need to know what was happening in the body of the loop, and what you mean by "works" or doesn't.

The for loop statement consists of 3 parts - the initialization section, the continue condition, and the increment section.

The initialization section (i = 0 in both loops) is performed before the loop starts.
The continue condition is checked. If true, the body of the loop is executed once.
The increment section is performed at the end of the loop.

Then, the continue condition is checked, and the loop body and increment section repeats, until the continue condition is false.

In the first loop, the continue condition is i < 10, which will be true for i = 0, 1, 2, ..., 8, and 9.
In the second loop, the continue condition is i == 10, which will be true for i = 10 only.

So, in the second case, since i is not 10 initially, the continue condition is false, and the body of the loop never executes.

OMG.. lol. of course!! what was i thinking? XD
in my mind it's the for loop of vb: "for i=0 to 10". for days!

so it's just like while(){... but with the initial and incremental setting within the same line.

Thanks a lot PaulS!!!

MartinGS:
so it's just like while(){... but with the initial and incremental setting within the same line.

It's not like while. A while loop doesn't not have to have a pre-defined number of iterations and a for loop does, unless you mess around with the iterator, which is forbidden by programming god(s). A while loop is often used to wait for a specific condition to become true, like:

while (button not pressed)
{
just wait
}

Do stuff since button is pressed.

One more thing, you can use while to do for's work or vise visa but that is like using a screw driver to jab holes. You can but you're not supposed to be.

It's not like while

It is exactly like a while.,
for (i = 0; i < 10; ++i) is precisely the same as

i=0;
while (i < 10) {
  //do stuff ... or not.
  ++i;
}

AWOL:

It's not like while

It is exactly like a while.,
for (i = 0; i < 10; ++i) is precisely the same as

i=0;

while (i < 10) {
  //do stuff ... or not.
  ++i;
}

You can use for loop to process not pre-determined number of iterations or while loop to do fixed number of iterations but my point is use the right control loop for the right original purpose.

@liudr

imho the for loop is not necessary for a fixed amount of times, but it is definitely the most suitable for fixed amount of iterations, like iterating an array or a matrix.

There are enough examples where for is used differently:

e.g. for (int i=0; a[ i] !=0; i++) { ... } does some action until an array element with content 0 is found (e.g. null terminated char array)
or with pointers for (char *p = &a[ 0], char *q = &b[ 0]; *p=*q; p++, q++) ; // sort of strcpy(a,b)
or the endless loop for( ; ; ) {...} ; no fixed amount either

Technically speaking every for loop can be rewritten into a while loop. However the do ... while() construct can't be rewritten in a for loop so easily as the moment of testing the condition is different - before loops body versus after loops body.

Although every for loop can be rewritten as a while loop there is a single point of attention and that is the scope of the iterator i. Look at the next 3 pieces of code:

for (int i=0; i< 10; i++) { ... }
The int i only exists in the for loop ....

int i=0;
for (i=0; i<10; i++) {...}
The int i will still exist after the for loop ...

int i=0;
while (i< 10) { ......; i++}
The int i will still exist after the while loop ...

This difference between the first one and the last two can be very usefull

We opened a Pandora's box :slight_smile:

do...while loop in for loop style:

for (int i=0;(i<10)||(i==0);i++)

:wink:

for (int i=0;(i<10)||(i==0);i++)

If i is 0, isn't that less than 10?

The difference between a while loop and a do/while loop is that the while body may never be executed, whereas the do/while body will always be executed at least once, since the continue condition is not checked until the end of the loop.

Can anyone explain to me why for(i = 0; i < 10; i++) { ...works, but for(i = 0; i == 10; i++) { ...won't?

The second term in the for statement causes the loop to CONTINUE if true, not STOP. You probably would get your expected results if you hadfor (i=0; i != 10; i++) { ...

PaulS:

for (int i=0;(i<10)||(i==0);i++)

If i is 0, isn't that less than 10?

The difference between a while loop and a do/while loop is that the while body may never be executed, whereas the do/while body will always be executed at least once, since the continue condition is not checked until the end of the loop.

My mistake, should be i=10;((i==10)¦¦(i<1));i++

Three strikes and your out.

My mistake, should be i=10;((i==10)¦¦(i<1));i++

If I starts at 10, the then i will never be less than 1.

In the interest of just messing around...

/* compile with gcc -o test test.c */

#include <stdio.h>

void main() {
  int i;

  i=0;
  printf("while() loop:\n");
  while (i < 10 ? printf("%d\n", i++) : 0);

  i=0;
  printf("for() loop:\n");
  for (;i < 10 ? printf("%d\n", i++) : 0;);
}

Compiles and runs - not sure how well it would work on the Arduino (you'd have to "Arduino-ize" it, and replace the printf() call, of course)...

:grin:

Paul,
We were on the "you can run the iteration at least once with do...while loop but not with for loop". I was demonstrating that you can run at least once with for loop as well. You just have to have an OR.

cr0sh:
In the interest of just messing around...

/* compile with gcc -o test test.c */

#include <stdio.h>

void main() {
 int i;

i=0;
 printf("while() loop:\n");
 while (i < 10 ? printf("%d\n", i++) : 0);

i=0;
 printf("for() loop:\n");
 for (;i < 10 ? printf("%d\n", i++) : 0;);
}




Compiles and runs - not sure how well it would work on the Arduino (you'd have to "Arduino-ize" it, and replace the printf() call, of course)...

:grin:

We're getting pretty far off OP now :cold_sweat:

I think the ternary operator ?: returns the return value of printf while the condition is met and then 0 went the condition is not met. Here is what I just glanced on www.cpluscplus.com for printf's return value, although I never knew it does return values:

Return Value
On success, the total number of characters written is returned.
On failure, a negative number is returned.

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

for (i=0; i != 10; i++) { ...

a ha! there you go!
i was thinking for i=0 until i==10, which is not the language this time.

This difference between the first one and the last two can be very usefull

aah very inspiring. in term of execution speed, and memory usage, is there any difference between the two?
in VBA, they say for loop is faster than while do loop. what about arduino?
oh, is speed ever matter? Microcontroller has less resources than PC, i guess it should matter more. But i have never got into the condition where speed is critical.

thanks again guys, these really opens up my horizon. I guess there really are many ways of saying a thing.

i have some more pondering on loops, but i will make new topic so that it's organized (trying to quit my messy habit).

You can try outputting microsecond time difference for both for and while loops. Many iterations are needed, maybe 32767 iterations :slight_smile:

@liudr

We opened a Pandora's box smiley
do...while loop in for loop style:
for (int i=0;(i<10)||(i==0);i++)

OK, but how if you create a for loop equivalent of this one - just as sample, no real code :wink:

int i = 0;
count = 0;
do 
{
  count++;
  i = random(6);    // random value between 0-5
} while (i != 0);

if we do it your way ==> for (int i=0; (i != 0) || (i==0); i++, count++); // oops!! that's forever ...

The generic solution introduces an additional variable to allow the first iteration

int i=0; // init
do
{
...
i++;
} while (i<10);

==>

for (int i=0, bool first = true;  i<10 || first ;  i++, first = false);

Note the drawback of this rewrite is a small performance penalty - testing & setting the flag - so still not 100% equivalent :wink:

This rewrite I got during an exam :wink:
Rob