C Constructs for Iteration - for Loops Continued
There are some shortcut ways to write the increment/decrement expression:
/* The following incrementing expressions are equivalent */
i = i + 1;
i += 1;
i++; /* this is one used most often in loops */
/* The following decrementing expressions are equivalent */
j = j - 1;
j -= 1;
j--;
What about ++j;?
Prefixing the increment or decrement operator means that the program will add (or substract) 1 before it does any calculation with or testing of the value. Sometimes this is what you want. Sometimes it does not make any difference. See the demo prePostIncrement.c.
You don’t have to add or subtract 1 - you can use any value:
/* The following loop prints all multiples of 5
* between zero and one hundred, inclusive.
*/
for (num = 0; num <= 100; num = num + 5)
{
printf("%d
", num);
}
The test condition will usually check the value of the loop variable against some limit. However, it can be a compound expression that tests additional expressions as well:
/* print the binary values of all decimal numbers from
* 0 to 100 unless the user tells you to stop.
*/
int value;
char response[8];
int bStop = 0;
for (value = 0; (value <= 100) && (bStop == 0); value++)
{
printf("%d in binary is %s
", value, convertToBinaryString(value));
printf("Do you want to stop? (Y/N)");
fgets(response,sizeof(response),stdin);
if (response[0] == ’Y’)
bStop = 1; }
การแปล กรุณารอสักครู่..