-
for loops - newbie q's
I understand that for loops are used as
for(variable = value)(relational expression)(inc dec value) {loop}
my question is, do you have to increment or decrement the variable set at the first of the function? and do you even have to set a variable at all? Like could you just say..
for (i != 0) {loop that modifies i} ..or would that just be a for loop acting as a while loop.
I cant see a whole lot of uses for the for loop.. from what I see it's just a while loop with a preset number of loops.
could anyone give me a simple example of other uses for the for loop besides the plain for(i = 1)(i <=20) (i++)
-
The good thing about for loops is that they do three functions in one. They set the starting value, evaulate the expression, and make the incremental change.
With a while loop you have to set the value before the while loop and make sure you put in the incremental change in the loop. I can't count the number of times I've forgotten to put the incremental change in a while loop.
Every different typle of loop has its strong points and weak points. Just need to identify them and use the best loop for the job.
-
so the only valid expression on the third part of the function is (var)++ or (var)--?
-
Nope, you can do other ones.
ie
for(i=0;i<x;i+=15)
It seems like you can do any math function. I don't know all the limits but i++ or i-- are not the only ones that can be done.
-
>I cant see a whole lot of uses for the for loop.. from what I see it's just a while loop with a preset number of loops.
A for loop is a subset of the while loop - a for loop is only used for counter-controlled repetition, and has very little other use. A while loop can be used for counter controlled repetition, but not very often. Normally a while loop is used to evaluate a condition, like an if/else statement.
Code:
while (condition1 == true){
do(someaction)
}
while (condition 1 != true){
do(someotheraction)
}
Try here for some examples of the for loop (go onto the other sections as well).
-
With for loops, you can have a loop without the increment value, without the condition, without the intialization, or any combination of two, or none of the above.
Code:
for( ; ; ) /*empty*/
{
if(condition) break;
}
i = 0
for(; i < 5; ) /*conditional only*/
{
printf("%d", i++);
}
Just two of the permitations of the for loop.
-
Thats pretty cool bigtamscot, never knew that. Of course in both cases I would have used a while loop.
-
>Of course in both cases I would have used a while loop
Well a while loop generally saves you time, but bigtamscot is right in what he's saying.
-
Ofcourse we would use a while loop first of all, just demonstrating flexability of for loop.