I know a for loops repeat an action some number of times. I read the mdm article on it.
Can someone explain like Im 5?
but I dont understand the syntax, especially the step++ part shown here
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log("Walking east one step");
}
Videos
for loop syntax - C++ Forum
syntax for 'for' loop
I believe a comma is only used if more than one variable is being initialized.
For example:
for (int i = 0, j = 1; i < 10; i++) { .... }
In this case, you'd have both i and j to use, giving you two variables to play with rather than one.
You can also do this on a normal line if you want, although it can sometimes get confusing, particularly with pointers.
Char a = 'a', b = 'b'; // initializes both a and b as chars
A for loop has three statements in it: initialization; condition; and iteration. The first two statements end with a semicolon just like any other statement.
I hope that clears it up :)
More on reddit.comWays of doing a for loop.
Roses are red
Violets are blue
Arrays start at zero
And for loops do too
Edit: Formatting is hard on mobile
More on reddit.comSyntactic sugar in C - (ab)using "for" loops
There is a caveat though. As the author said in the summary section, while the prologue/epilogue example should work in normal conditions, it would break (pun not intended) when you break or goto inside the loop. And break inside the loop happens a lot. Be careful when using this to manage resources. In C++, using a stack allocated object with a destructor in the initialization part can handle exceptional control flows.