Friday, April 18, 2008

Loop de loop.

In C there are 3 type of loops. The function of a loop is to repeatedly execute a set of instructions within that loop until some condition is met or indefinitely.

The type of loops are:-

While
Do..while
For

A loop will always execute instructions as long as the expression is true. True in C is any non zero value.

WHILE

Usage:
while (expression){ statement }

Portb=0b10101010;
while(1) {
Portb = ~portb;
Delay_ms(400);
}

In the code above, the loop will never end. The code between {…} is executed endlessly. This is usually used for main loops of programs the don’t end.

.
while(Portb.f1 == 0) {
.
.
}

This loop will repeat until the state of portb.f1 changes. Meaning when portb.f1 = 1 the loop exits.

Important point to notice is that the expression is evaluated before the code between {…} is executed. If expression is false then the entire code between {…} is skipped. If you want to execute the code at least once, then you need to use a do…while loop.

do…while

Usage:
do { statement } while (expression);

As mentioned above, the do while(as it is called) executes code between {…} at least once before deciding on continuing with the loop or not.

do {
CountUp++;
CountDn--;
.
.
.
} while(Portb.f4==1) ;


for()

for ([init-expression]; [condition-expression]; [increment-expression]) statement
note: square brackets indicate optional.

The for loop can be used like do or while loop, but I strongly recommend against it.

for( ; ;) {
CountUp++
CountDd—
.
.
}

This is an endless loop. There are only two way to exit this loop (or any endless loop).
That is using the break statement or branch out of the loop using the goto command. I personally, strongly discouraged the use of goto. Programming becomes unstructured and difficult to debug. Alright, back to the for loop.

init-expression it the initial value of the variable you want to start with.

condition-expression the loop must satisfy this condition to exit.

increment-expression here you increased or decrease your variable.

signed int CountUp =0, CountDn=0;
for(count=1; count <=3; count++) {
++CountUp;
--CountDn;
}


When Count is

CountUp

CountDn

1

1

-1

2

2

-2

3

3

-3

4

3

3



Before the loop begins it sets to to 1.
Then checks if count is equal to 3.
Increases the variable count by 1.

Since count is not equal to 3 it executes the code between { }, which increases CountUp and decreases CountDn.

When count is 4, the loop exits.

The for() can be use in other ways. But this is the most basic you will need to you.

No comments: