More about for loops

advertisement
More about for loops
The actions taken in a for loop as given here are:
for (i = 0; i <= 10; i++)
{
scanf ("%lf", &x[i] );
}
1. i=0, this assignment is made once only at the start of the for function.
2. evaluate i<=10. Answer is TRUE in this case.
3. therefore carry out the actions in { } ie. read a single double precision
number and place it in the array x at element given by i.
4. only now is i incremented (i++) ie i = i+1.
5. re-evaluate i<=10. Still TRUE so read another number.
6. increment i again.
7. repeat this until i<=10 is FALSE.
8. now immediately skip the actions given in { } and move to the next line
of code.
The relationship between for loops and
P
A maths problem that requires eg.
N
X
xi
i=0
can be naturally written in C using for loops as
for (i = 0; i <= N; i++)
{
sum = sum + pow(x,i);
}
You can take it that the value of N has been assigned earlier in the program.
Another new C function has appeared here! It’s very useful when you want to
raise a number x to power y.
In C: xy is calculated by calling pow(x,y).
Download