Page 54 - Programming Microcontrollers in C
P. 54
Program Flow and Control 39
int main(void)
{
int guess,i;
for(i=1,guess=5;i!=guess;)
{
i=guess;
guess=(i+(10000/i))/2;
}
printf(“The square root of 10000 =
%d\n”,guess);
return 0;
}
Recall that the for allows three arguments. Not all arguments
are necessary for proper execution of the for. In this case, only two
arguments are included. The first argument is really two initializa
tion arguments separated by a comma operator. When the comma
operator is used, the statements separated by commas are each evalu
ated until the semicolon is found. At this time, the initialization is
terminated. By the way, the comma operator can be used in normal
code sequences so that you can string several statements in a row
without separating them with semicolons. The second argument of
the for construct is i != guess. The for loop will execute so
long as this expression is TRUE. Note that there is no third statement
in the for invocation.
This argument is where you would normally place the change in
i that is to take place at the end of each loop. In this case, the opera
tion on i is i=guess. If this expression were used for the third
argument, at the end of the first loop, the second argument would be
FALSE, and execution of the calculation would be prematurely ter
minated.
The Do/While Construct
Another looping structure is the do/while loop. Recall that the
argument of a while statement is tested prior to executing the state
ment following. If the argument of the while is FALSE to begin
with, the statement following will never be executed. Sometimes, it is