Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Michael Hernandez
1,365 PointsHelp with for statements?
I'm a bit confused as to what is going on when creating a for statement. Where it will often come in the following format:
for (Class something : mSomething)
I get that it is saying something like for within the class we are working in..., but beyond that I am a bit confused.
2 Answers
andren
28,558 PointsActually the first part is more of a variable declaration. Basically the for statement states this: "Create a variable of type X called Y, then assign it the items found in collection Z", where X is the first word, Y is the second word and Z is the third word.
When a for statement starts it looks at the collection that it has been given (the word on the right of the colon) and pulls out the fist item of said collection and then assigns it to the variable described on the left.
Then it runs the code within the loop. Once it has run that code it pulls the second item out of the collection and assigns it to that variable, and runs the code again, then it pulls out the third item and assigns that to the variable and so on. It continues doing that until it has gone though all of the items in the collection, and then it stops the loop automatically.
That process makes it easy to run a group of code on each individual item in the collection.
ofir moalmi
2,161 Pointsfor(int counter=1; counter<11; counter++){
}
is equal to
int counter =1;
while(counter < 11){
counter++
}
just means for every time counter is less than 11, increase it by 1.