Sign in to follow this  
zalo

The for loop error [solved]

Recommended Posts

I'm new to C++ and the game making universe, but am trying to learn as best as I can. I'm currently teaching myself from a C++ for dummies book, but am stuck. When I tried to enter this block of code in the my compiler, I got a result completely opposite to what was supposed to occur. http://i34.photobucket.com/albums/d144/Zalo10/error-1.jpg The code. http://i34.photobucket.com/albums/d144/Zalo10/error1.jpg The result. The result I was looking for was 100, not 5050 I've compiled this same code in Dev C++ and Visual Studio 2008. Am I doing anything wrong? Or is it just the computer. [Edited by - zalo on August 14, 2008 5:45:57 PM]

Share this post


Link to post
Share on other sites
Why would you expect this to be 100? What do you think the loop does? What does "x" represent after the for-loop is done?

Share this post


Link to post
Share on other sites
The result of 5050 is correct. That for loops adds the numbers 1 through 100 (1 + 2 + 3 + 4 + ... + 100) into the variable x. That is 5050.

What you probably want in the for loop is x = x + 1. That is the number one, not the variable i. Since you copied this from a book, it may be hard to read with typical fixed-spaced fonts used.

Share this post


Link to post
Share on other sites
I understand what you are saying, and what you suggested worked, but the book I was reading from does in fact say x += i.

It has to be a typo.

Thanks for your help.

This is one of the more friendly communities, I've been to.

[Edited by - zalo on August 14, 2008 6:03:32 PM]

Share this post


Link to post
Share on other sites
A for loop statement usually consists of 3 things.

1) a initial value.
2) some condition on which the loop will continue while the condition is met.
3) some modifier to the initial value.

all of which are separated by ;'s

in the case of:

for (i=1; i<=100; i++) {

//some other code to execute
}



the first part i=1 sets the initial value of i to 1

the second part says keep looping so long as i is less than or equal to 100

the final part will increment i by 1 every iteration. (I think this is where you're getting hung up at)

basically the value of i will change every time the loop iterates. since you have i++ at the end of the for loop, the value of i will increase by 1 each iteration.

inside the loop you have the line x += i;

so since the value of i changes as follows: 1,2,3,4,5,6,7....99,100

the value of x will be equal to 0+1+2+3+4+5+6+7+8+9+etc...

Probablly not a technically accurate explanation but hopefully you'll see what you're misunderstanding.

-=[ Megahertz ]=-

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this