Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

cybrscot

macrumors 6502
Original poster
Dec 7, 2010
282
0
Somewhere in Southeast Asia
A for loop has 3 expressions as I know, but the 1st expression in an example in my book is a variable that is initialized to 10, i = 10;

What I want to know is how do I know what I should initialize the variable to? My book says, " Since the first and third expressions in a for stmt are executed as statements, their values are irrelevant."

It offers no clearer explanation. Why is it irrelevant? Why did they initialize i = 10? Why not i = 0, why so arbitrary?

I have to work out a problem, but I don't have an idea as to what the rhyme or reason is for selecting the value/initializing the variable.

Thanks
 
A for loop has 3 expressions as I know, but the 1st expression in an example in my book is a variable that is initialized to 10, i = 10;

What I want to know is how do I know what I should initialize the variable to? My book says, " Since the first and third expressions in a for stmt are executed as statements, their values are irrelevant."

It offers no clearer explanation. Why is it irrelevant? Why did they initialize i = 10? Why not i = 0, why so arbitrary?

I have to work out a problem, but I don't have an idea as to what the rhyme or reason is for selecting the value/initializing the variable.

Thanks

It depends what you are counting to and from:

Code:
for (int i = 0; i < 10; i++)  // Start counting at 0, loop 10 times
for (int i = 1; i < 10; i++) // Start counting at 1, loop 9 times
for (int i = 10; i > 0; i--) // Count backwards from 10, loop 10 times

It's useful to start at zero because 'for' loops are often used for looping through arrays, which are zero based, but it honestly depends entirely on your need for the program.
 
i = 10 evaluates to 10. This is useful so you can say x = y = 5, checking for a non-null assignment in a conditional, etc

The book means that the result of the expression for the first and third elements of the for do not get used. The side effects, i being set to 10, or a ++ to increment a control variable, obviously have a major impact on how the loop works, but only the result of the second statement is used to determine the behavior of the loop.

What you initialize a control variable to in the first statement depends on what you need to achieve in your loop. Do you need to loop from 0 to 4? 4 to 1000 incrementing by 3? 9 to -2? Wherever you need this variable to start, that's what you set it to. 0 is a popular choice because arrays start with index 0.

If you have a particular problem and don't know where to start, post it and what you think you should start with, and we can help you with working it out.

-Lee
 
They aren't irrelevant. But I guess perhaps in the context of the surrounding text in the book?

A for loop is just a short hand, more compact way of doing this:

Code:
int i = 10;

while( i < 20 ) {
        printf("%d\n", i);
        i++;
}

Instead everything is written on one line.

Code:
for(i = 10; i < 20; i++)

The initialization is done once before the loop runs, then before each iteration the condition is checked, if it passes the loop is executed and i is incremented. After that the condition is checked again, and so on.
 
They aren't irrelevant. But I guess perhaps in the context of the surrounding text in the book?

A for loop is just a short hand, more compact way of doing this:

Code:
int i = 10;

while( i < 20 ) {
        printf("%d\n", i);
        i++;
}

Instead everything is written on one line.

Code:
for(i = 10; i < 20; i++)

The initialization is done once before the loop runs, then before each iteration the condition is checked, if it passes the loop is executed and i is incremented. After that the condition is checked again, and so on.

I had worded this differently, but re-reading this is accurate, just not how I think of it.

-Lee
 
Last edited:
They aren't irrelevant.

The book means that the result of the expression for the first and third elements of the for do not get used. The side effects, i being set to 10, or a ++ to increment a control variable, obviously have a major impact on how the loop works, but only the result of the second statement is used to determine the behavior of the loop.

To refine Lee's point.

I could say
Code:
for(((i = 0)!=-999); i < 20; (i++>5))
and still have the same effect as the loop without the conditionals in the first and third expressions. What they evaluate to is irrelevant it's the side-effects that are important.

B
 
It depends what you are counting to and from:

Code:
for (int i = 0; i < 10; i++)  // Start counting at 0, loop 10 times
for (int i = 1; i < 10; i++) // Start counting at 1, loop 9 times
for (int i = 10; i > 0; i--) // Count backwards from 10, loop 10 times

It's useful to start at zero because 'for' loops are often used for looping through arrays, which are zero based, but it honestly depends entirely on your need for the program.

Oh, I see, I was wondering at first how you said your examples above loop 10 times, 9 times, and 10 times, I was originally looking at the "iteration" or expr 2 in your above example, and thinking that the 10 meant it would loop 10 times, and the 0, zero times. But I see now that the amount of times the loop loops (if that makes any sense) is actually the difference between the expr1 and the expr2. From 0-10, then from 1-10, then from 10-1. I get it.


My problem was this...

"Write a program that prompts the user to enter a number n, then prints all even squares between 1 and n. For example, if the user enters 100, the program should print the following."
4
16
36
64
100.

At first I tried to think of how to "on paper" establish a pattern that would go from 4 to 16 to 36, etc. I didn't think there was any way I could increment any variable by 1, like i++, to get there. I don't know of any way to increment a variable by any amount greater than 1, like i+++, or i++++. Then, as I was trying to go to sleep, it came to me (long time since I've been in a math class, so give me a break) I just needed to go from 2 to 4 to 6 to 8 to 10, etc because the squares of even numbers are all even numbers, and consecutively as well. So I figured out that I'd want to do something from 2, then add 2, then add 2, etc.

I wasn't sure how to represent my thinking in terms of code, so I cheated on this one. The book has just a couple of the programs in the exercises on it's website already worked out, and this was one of them.

I felt more comfortable looking at the completed code as a tutorial or example that I could study and learn from. Every once and I while a construction worker has got to see a completed house to serve as a guide and see the big picture of what he's there to accomplish.

I got to thinking the other day..... as I'm new at this, I really haven't seen any code in my entire life, except the few examples in each chapter. Imagine being given a task to build something that you've never seen or used before, given all the tools and parts and supplies, being told to put it all together to make what's in the picture! Only to have been shown a photo or two of what your finished product should look like? Pretty difficult. That's what I've been doing through 6 chapters so far. Trying to use what I learned in the chapter, to build something I've never seen before and was completely unfamiliar with.

So with this particular problem, I took a different route. I decided to take a walk through the completed house, and examine it's build, structure, and layout, go through the front door, then out the back, then in through the back and out the front, familiarizing myself with what I'm being asked to build chapter after chapter. I think it will help me with future problems. Let's hope so!

Thanks, here's the code...

Code:
#include <stdio.h>

int main(void)
{
  int i, n;

  printf("Enter limit on maximum square: ");
  scanf("%d", &n);

  for (i = 2; i * i <= n; i += 2)
    printf("%d\n", i * i);

  return 0;
}
 
To refine Lee's point.

I could say
Code:
for(((i = 0)!=-999); i < 20; (i++>5))
and still have the same effect as the loop without the conditionals in the first and third expressions. What they evaluate to is irrelevant it's the side-effects that are important.

B

Of course they are not irrelevant. Obfuscating them proves nothing, you could do the same with the conditional and it would still not make it irrelevant. Irrelevant suggests that you can leave them out of the loop all together, or that their values doesn't impact the loop. I suppose if infinite loops are the the goal they are irrelevant.
 
Of course they are not irrelevant. Obfuscating them proves nothing, you could do the same with the conditional and it would still not make it irrelevant. Irrelevant suggests that you can leave them out of the loop all together, or that their values doesn't impact the loop. I suppose if infinite loops are the the goal they are irrelevant.

The *result* of the expressions, or what they evaluate to, is what's irrelevant. Their side effects are critical.

-Lee
 
The *result* of the expressions, or what they evaluate to, is what's irrelevant. Their side effects are critical.

-Lee

Please. It's a confusing way of putting it.

Let's look at only the condition.

Code:
for(; i < 10;)

Code:
for(i = 10; i < 10;)

Code:
for(i = 0; i < 10; i--)
 
I don't know of any way to increment a variable by any amount greater than 1, like i+++, or i++++.

You can always do it the obvious way:
Code:
[COLOR="Blue"]i = [/COLOR][COLOR="Red"]i + 2[/COLOR];
The red part means "Calculate the value of i plus 2". The blue part means "Store the result of the calculation into i."

If you're having this much trouble with arithmetic, you might want to practice the fundamentals more. Maybe take some basic arithmetic problems from a grade-school textbook and write code for them.
 
You can always do it the obvious way:
Code:
[COLOR="Blue"]i = [/COLOR][COLOR="Red"]i + 2[/COLOR];

Which in C shorthand can be replaced with
Code:
i += 2;

subsonix, think of it this way. If I wrote two functions "assign(i,0)" and "increment (i,1)" to replace "i=0" and "i++" the return value of those functions are ignored in a for loop, and thus completely irrelevant. What else they do maters a lot, but not what they evaluate to/return.

B
 
subsonix, think of it this way. If I wrote two functions "assign(i,0)" and "increment (i,1)" to replace "i=0" and "i++" the return value of those functions are ignored in a for loop, and thus completely irrelevant. What else they do maters a lot, but not what they evaluate to/return.

B

No, I don't. Let't look at this in context shall we? I'm answering this question, here.

What I want to know is how do I know what I should initialize the variable to? My book says, " Since the first and third expressions in a for stmt are executed as statements, their values are irrelevant."

It offers no clearer explanation. Why is it irrelevant? Why did they initialize i = 10? Why not i = 0, why so arbitrary?

What you guys are doing is engaging in a discussion similar to what kills is not the fire but the heat. I don't have the complete text, but I think it's a pretty confusing way of introducing this in a book based on what was given here. Which is why I said: "But I guess perhaps in the context of the surrounding text in the book?"

What is evaluated to determine if the loop should continue is the condition, I already said so in my first post.
 
Let't look at this in context shall we? I'm answering this question, here.

It offers no clearer explanation. Why is it irrelevant?

You are ignoring/contradicting this critical part of the question which is what we are trying to explain. It is the author's argument, not mine or Lee's, that the return value of the expressions is irrelevant. He's right, it's just a very odd/confusing way to put it. In that I fully agree with you. EDIT: I also think that thinking of the for loop as simply shorthand for the while loop you presented is absolutely the right way to teach it.

Overall as seen through cybrscot's posts I think the book seems to spend a lot of time looking at these kinds of esoteric issues before getting to (IMHO) more basic useful stuff that would be useful sooner.

As such, I think it is probably a decent book to use in a classroom setting, but hard for an absolute beginner like crybrscot to use to learn it on their own because of this.

B
 
Last edited:
You are ignoring/contradicting this critical part of the question which is what we are trying to explain.

Well, to my defense this is all I had to go by.

"Since the first and third expressions in a for stmt are executed as statements, their values are irrelevant."

That alone, doesn't give enough information. The whole for loop is a statement, and the initialization part is a definition, possibly declaration as well in case of C99. The point is, is the definition part of the evaluation? Of course not! But that does not make it irrelevant, I suspect some text is missing here to explain that part. The fact that the for loop uses semicolons to separate it's fields, gives a clear hint that these are not directly related to each other.
 
The whole for loop is a statement, and the initialization part is a definition, possibly declaration as well in case of C99.

I think the whole point the author is trying to make is that the for loop is

Code:
for(statement1;expression2;statement3){...}

using your construct this translates to:

Code:
statement1;

while( expression3 ) {
        ...
        statement2;
}

the (return) value of statement1 and statement2 is irrelevant because nothing is done with it. Almost as if you cast them to void. But the (return) value of expression2 is actually important.

statement1 doesn't have to be a simple definition or declaration, it could be a more complex function incorporating more of the code before the loop (e.g. including input), while statement2 could be a function that includes the whole body of the loop if you wanted it to.

The problem with going into this discussion now is that the author seems to have avoided functions until now, and as can be seen from cybrscot's code he has even avoided talking about return values much since he uses "main() {}" instead of "int main (void){}".

B
 
I think the whole point the author is trying to make is that the for loop is

Code:
for(statement1;expression2;statement3){...}

using your construct this translates to:

Code:
statement1;

while( expression3 ) {
        ...
        statement2;
}

Yes, I know this is the point he is trying to make. And, perhaps he achieves that as well. I don't know, I have only seen one sentence.

the (return) value of statement1 and statement2 is irrelevant because nothing is done with it. Almost as if you cast them to void. But the (return) value of expression2 is actually important.

No, it's a mistake to take it as far as saying that it's irrelevant, because it's not. Let's take a simple increment operation by one.

i++

or

i = i + 1;

As you can see, the increment operator does return a value. That value is then given to i. This value is later directly related to what the evaluation will result in.

statement1 doesn't have to be a simple definition or declaration, it could be a more complex function incorporating more of the code before the loop (e.g. including input), while statement2 could be a function that includes the whole body of the loop if you wanted it to.

The fact that the example I gave was a definition and declaration, does not mean that anything else is impossible. I hope this is clear.
 
This value is later directly related to what the evaluation will result in.
In this case yes they are related, but it is not necessarily so, and it is the "side effect" of actually changing the value of the loop counter that is what matters.

FWIW the extended quote from the author is:

Since the first and third expressions are executed as statements, their values are irrelevant - they're useful only for their side effects. Consequently, these two expressions are usually assignments or increment/decrement expressions.

It does actually follow a Q&A discussion of the equivalent while loop and the following passage:

As this pattern shows, expr1 is an initialization step that's performed only once, before the loop begins to execute, expr2 controls loop termination (the loop continues executing as long as the value of expr2 is nonzero) and expr3 is an operation to be performed at the end of each loop iteration.

It then goes on to describe several "idioms" counting up and down.

(Thanks Amazon look inside).

B
 
In this case yes they are related, but it is not necessarily so, and it is the "side effect" of actually changing the value of the loop counter that is what matters.

Well, as far as I'm concerned anything whose side effects is critical to the outcome is not irrelevant. :D

Enough of this, ok? :)
 
Well, as far as I'm concerned anything whose side effects is critical to the outcome is not irrelevant. :D

Enough of this, ok? :)

:p Take it up with K. N. King he started it.

Having now read the whole section I do think it's less out of context than cybrscot implied, yet still beyond the level of comprehension I would expect of most readers reading this as their first book on programming with only the limited info he has provided so far.

B
 
Well, as far as I'm concerned anything whose side effects is critical to the outcome is not irrelevant. :D
No one said that the side effects are irrelevant.
The statement was that the value was irrelevant.
++i and i++ have identical side effects, but different return values.
In a context that uses the value, the difference is very relevant
In a context that ignores the value, the difference is not.
for(; ++i ; ) and for(; i++ ; ) have distinctly different behaviour
for(; ; ++i ) and for(; ; i++ ) have identical behaviour
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.