“Finite” Loops [ for ]

The function for() is a special case of using a while () to repeat some behavior a few times with a variable change.   Let’s say that you want to repeat a display [printf() function] while changing a parameter a specific number of times: Say you wanted your robot to display a count-down,  3 to 1, in one second intervals, before it goes.

[This example also introduces a function <go_forward()> and assumes a demobot, as used in the introduction, with two motors on ports #’0′ & ‘3’. driving the wheels.]

Write and download this code:

void go_forward(); 
 int main()
   int i; // declare variable
   for(i=3;i>0;i--) /*this causes it to loop 3 times (because 3, 2, and 1 are all 
   more than 0)*/
      printf("%d,\n",i); //prints the value of i each time through the loop
      msleep(1000); // wait for 1 sec each time through the loop 
   printf("Let's go!!!\n");
  } // program ends here
void go_forward()

After you run it – you can see that it counts 3, 2, 1 – one per second before it says “Let’s go!!” and dives forward.

Let’s look at the for() command:

for(i=3;i>0;i- –) { }

There are three items within the parentheses separated by semicolons(;)

Initialization: Sets the beginning value for our count variable

Test: Sets the test condition that will keep the loop going while it is true

Increment (or decrement): Sets the value of the count increase or decrease (i– is short-hand for i=i-1)

In other words: The for loop is a special type of while loop.

So for(i=3;i<0;i- -) {some code }

is the same as a repeat loop using while():


while (i>0)


some code

i=i-1; // same as i- –


NEXT: Printing


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s