The Two General Loops

There are two general loops, the while loop and the for loop.  There are variations on how the loops are implemented in different languages but the developer usually have two scenarios:  he knows how many times to loop or he needs to loop until a condition becomes true.

The for loop is used when the developer knows how many times to perform the loop.  For example, he needs to print the ascii code of the characters of the alphabet.  In PHP and in C (remove the $ sign from the variable if using C language), this can be done this way:

for ($i = 65; $i < 91; $i++) {
printf(“%c\n”, $i);
}

If we didn’t know that there are 26 characters in the alphabet but we know that the last character is the letter ‘Z’, then we would need to use a while loop:

$i = 65;
while (chr($i) != ‘Z’) {
printf(“%c\n”, $i);
$i++;
}

Submit a Comment