Loops are the reason, why programs can repeat some functions again and again. Therefore it is important to know how to program with them. Actually loops and conditionality are the two basic elements of programming. In
while (expression)
statement
expression is evaluated. If it is non-zero, statement is executed and is re-evaluated. The cycle continues until expression becomes zero, at which point execution resumes after statement. In other words loop continues as long as expression is TRUE. This helps us to create eternal loop: while(1){…}
The for statement
for (expr1; expr2; expr3;)
statement
is equivalent to
expr1;
while (expr2)
{
statement
expr3;
}
except for the behavior of continue, which is described later.
Grammatically, the three components of a for loop are expressions. Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a relational expression. Any of the three parts can be omitted, although the semicolons must remain. If the test, expr2, is not present, it is taken as permanently true, so
for ( ; ; )
{
…
}
is an infinite loop (like while(1){} too), presumably to be broken by other means, such as a break or return.
Whether to use while or for is largely a matter of personal preference.
Comparison
for (i=0; i
{ … } |
i=0; while (i < n) { … i++; } |
Finally a pair of examples for using nested loop. Both of these functions will need a main function. These examples are also useful in your programs. The first function sorts an array of integers.
/*Shellsort: sort v[0]...v[n-1] into increasing order*/ void shellsort(in v[], int n) { int gap, i, j, temp; for(gap = n/2; gap>0; gap /= 2) for(i=gap; i<n; i++) for (j=i-gap; j>=0 && v[j] > v[j+gap]; j-=gap) { temp = v[j]; v[j] = v[j+gap]; v[j+gap] = temp; } }
Next function reverses the string s in place, string.h headerfile is needed for strlen-function, which counts the number of characters in table s.
/*reverse: reverse string s in place*/ void reverse(char s[]) { int c, i, j; for(i=0; j=strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
NOTE! Exercises for that chapter can be found in quizzes Exercises 4 and P3-4 where these skills will also be tested. It is also important that the student does these examples above.