C Constructs for Iteration - while Loops
while (condition)
{
statement1;
statement2;
statement3;
...
}
condition is a logical expression which will evaluate to either true or false.
The statements in the loop body (the statements inside the curly braces) are repeated as long as the condition remains true.
The loop body may contain a statement that will potentially change the value of the condition from true to false. (If there is no such statement the loop will continue forever. You may or may not want that.)
If condition is false the first time the code reaches the while test, the statements in the loop body will not be executed even once.
Example
char inputData[32];
int value = 0;
long total = 0;
/* Loop, getting values from the user and adding them
* to the total, until the user enters a negative value.
* Then stop.
*/
while (value >= 0 )
{
printf("Enter a value, -1 to stop: ");
fgets(inputData,32,stdin);
sscanf(inputData,"%d",&value);
if (value >= 0)
{
total = total + value;
}
}
C Constructs for Iteration - while Loops
while (condition)
{
statement1;
statement2;
statement3;
...
}
condition is a logical expression which will evaluate to either true or false.
The statements in the loop body (the statements inside the curly braces) are repeated as long as the condition remains true.
The loop body may contain a statement that will potentially change the value of the condition from true to false. (If there is no such statement the loop will continue forever. You may or may not want that.)
If condition is false the first time the code reaches the while test, the statements in the loop body will not be executed even once.
Example
char inputData[32];
int value = 0;
long total = 0;
/* Loop, getting values from the user and adding them
* to the total, until the user enters a negative value.
* Then stop.
*/
while (value >= 0 )
{
printf("Enter a value, -1 to stop: ");
fgets(inputData,32,stdin);
sscanf(inputData,"%d",&value);
if (value >= 0)
{
total = total + value;
}
}
การแปล กรุณารอสักครู่..
