04 May 2012

For Loops

Sometimes we need to write a program where a block of code needs to be repeated. Rather than write a code over and over, we use one of the Repetition Structures available in programming languages.

The simplest of these structures is the For Loop.

This loop is used when a set of instructions is to be repeated a predetermined number of times.

When you put your program into a loop, you must ensure that the loop will eventually end. In For Loops, this usually involves counting the number of repetitions.

Counting involves incrementing the value of a variable - for example Ctr = Ctr + 1;

The 'C' language has some shorthand methods to do this kind of arithmetic.
Ctr = Ctr + 1; Ctr++; and Ctrl += 1;    all mean exactly the same thing in 'C'.
Ctr--;         will subtract 1 from Ctr.
Ctr += 2;    will add two to Ctr

In 'C' the simplest form of For Loop is coded:
int Ctr;
for(Ctr = 0; Ctr < 10; Ctr++)
    printf("This is Loop %d\n", Ctr);

This code will cause 10 lines of output, with values of Ctr from 0 to 9.

Ctr = 0 Sets the integer variable named Ctr to an initial value of Zero.
Ctr < 10 Tests the value of Ctr; If this test is true, the code in the loop will be executed.
Ctr++ Increases the value of Ctr for re-testing. NOTE: Ctr is changed at the end of the loop before the next test. The loop ends when Ctr reaches 10, and the condition is no longer true.

int Ctr;
for(Ctr = 5; Ctr < 10; Ctr++)

This code causes 5 lines of output as Ctr goes backwards from 5 to 1, in steps of -1.

No comments:

Post a Comment