+ 1
For Loops Initialization - do we need to identify the variable?
I noticed that in the for loops that the variable that's being used always starts with int. Does that mean that when doing a for loop, we have to define the variable there and then? For Example: | int x=3 | | for (x=3; x>=9; x++) { | cout << x << endl; | } // is this acceptable?
4 Réponses
+ 24
yes your example is acceptable
as in any program u need declared variables and in cpp u can declare variables any where in program at the time u required it and that why in for loop variable is declared there
and it is also for reducing the risk of error i.e.,an defined symbol
+ 9
Yes you have to declare that it's an int. ( as opposed to JS where you don't have to)
+ 2
That is done in order to restrict the variable scope to the for loop only.
for (int x=1;x <=9;i++) {
// todo
}
is okay and
int x;
for (x=1;x <=9;i++) {
// todo
}
is also okay
+ 1
You can omit all the terms inside a for loop statement if you want, but that will lead to an infinite loop.
Based on your example, you could have just written :
int x = 3;
for( ; x >= 9; x++){
// code
}
You don't have to define the variable that needs to meet a condition inside the for loop.
Also, just to mention, based on your input, the for loop will never run (3 is never greater or equal to 9).